# Continuously updating word count import unohelper, uno, os, time from com.sun.star.i18n.WordType import WORD_COUNT from com.sun.star.i18n import Boundary from com.sun.star.lang import Locale from com.sun.star.awt import XTopWindowListener #socket = True socket = False localContext = uno.getComponentContext() if socket: resolver = localContext.ServiceManager.createInstanceWithContext('com.sun.star.bridge.UnoUrlResolver', localContext) ctx = resolver.resolve('uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext') else: ctx = localContext smgr = ctx.ServiceManager desktop = smgr.createInstanceWithContext('com.sun.star.frame.Desktop', ctx) waittime = 5 # seconds def printOut(txt): if socket: print txt else: model = desktop.getCurrentComponent() text = model.Text cursor = text.createTextCursorByRange(text.getEnd()) text.insertString(cursor, txt + '\r', 0) def hotCount(st): '''Counts the number of words in a string. ARGUMENTS: str st: count the number of words in this string RETURNS: int: the number of words in st''' startpos = long() nextwd = Boundary() lc = Locale() if not lc.Language: # jj lc.Language = 'en' numwords = 1 mystartpos = 1 brk = smgr.createInstanceWithContext('com.sun.star.i18n.BreakIterator', ctx) nextwd = brk.nextWord(st, startpos, lc, WORD_COUNT) while nextwd.startPos != nextwd.endPos: numwords += 1 nw = nextwd.startPos nextwd = brk.nextWord(st, nw, lc, WORD_COUNT) return numwords def updateCount(dialogModel, wordCountModel, percentModel, charCountModel, goal): # jj '''Updates the GUI. Updates the word count and the percentage completed in the Tkinter GUI. If some text of more than one word is selected, it updates the GUI based on the selection; if not, on the whole document.''' model = desktop.getCurrentComponent() try: if not model.supportsService('com.sun.star.text.TextDocument'): return except AttributeError: return sel = model.getCurrentSelection() try: selcount = sel.getCount() except AttributeError: return if selcount == 1 and sel.getByIndex(0).getString == '': selcount = 0 selwords = 0 selchars = 0 # jj for nsel in range(selcount): thisrange = sel.getByIndex(nsel) atext = thisrange.getString() selwords += hotCount(atext) selchars += len(atext) # jj if selwords > 1: wc = selwords cc = selchars # jj else: try: wc = model.WordCount cc = model.CharacterCount # jj except AttributeError: return wordCountModel.Label = str(wc) charCountModel.Label = str(cc) # jj dialogModel.Title = "Word Count (%s)" % model.Title # jj if goal != 0: pc_text = '(%.2f%%)' % (100 * (wc / float(goal))) # jj percentModel.Label = pc_text else: # jj percentModel.Label = '(??%)' # jj # This is the user interface bit. It looks more or less like this: ############################### # Word Count _ o x # ############################### # _____ # # 451 of |500| (90.20 percent)# # ----- # ############################### # The boxed `500' is the text entry box. class WindowClosingListener(unohelper.Base, XTopWindowListener): def __init__(self): global keepGoing keepGoing = True def windowClosing(self, e): global keepGoing keepGoing = False e.Source.setVisible(False) def addControl(controlType, dlgModel, x, y, width, height, label, name = None): control = dlgModel.createInstance(controlType) control.PositionX = x control.PositionY = y control.Width = width control.Height = height if controlType == 'com.sun.star.awt.UnoControlFixedTextModel': control.Label = label elif controlType == 'com.sun.star.awt.UnoControlEditModel': control.Text = label if name: control.Name = name dlgModel.insertByName(name, control) else: control.Name = 'unnamed' dlgModel.insertByName('unnamed', control) return control def loopTheLoop(controls): # jj while keepGoing: try: goal = int(controls.goalModel.Text) except: goal = 0 updateCount(controls.dialogModel, controls.wordCountModel, controls.percentModel, controls.charCountModel, goal) # jj time.sleep(waittime) if not socket: import threading class UpdaterThread(threading.Thread): def __init__(self, controls): # jj threading.Thread.__init__(self) self.controls = controls # jj def run(self): loopTheLoop(self.controls) # jj class Controls(object): pass def wordCount(arg = None): '''Displays a continuously updating word count.''' dialogModel = smgr.createInstanceWithContext('com.sun.star.awt.UnoControlDialogModel', ctx) dialogModel.PositionX = 300 dialogModel.PositionY = 20 dialogModel.Width = 160 + 14 # jj dialogModel.Height = 16 dialogModel.Title = 'Word Count' addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 6, 2, 24, 14, 'chars:', 'lblC') # jj # character counter lblCc = addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 17, 2, 26, 14, '', 'lblCc') # jj lblCc.Align = 2 # Align right addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 49, 2, 24, 24, 'words:', 'lblW') # jj # word counter lblWc = addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 59, 2, 24, 14, '', 'lblWc') # jj lblWc.Align = 2 # Align right addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 85, 2, 10, 14, 'of') # jj addControl('com.sun.star.awt.UnoControlEditModel', dialogModel, 93, 2, 24, 14, '', 'txtGoal') # jj addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 118, 2, 50, 14, '(??%)', 'lblPercent') # jj controlContainer = smgr.createInstanceWithContext('com.sun.star.awt.UnoControlDialog', ctx) controlContainer.setModel(dialogModel) controlContainer.addTopWindowListener(WindowClosingListener()) controlContainer.setVisible(True) controls = Controls() controls.dialogModel = dialogModel controls.goalModel = controlContainer.getControl('txtGoal').getModel() controls.charCountModel = controlContainer.getControl('lblCc').getModel() # jj controls.wordCountModel = controlContainer.getControl('lblWc').getModel() controls.percentModel = controlContainer.getControl('lblPercent').getModel() if socket: loopTheLoop(controls) # jj else: uthread = UpdaterThread(controls) # jj uthread.start() keepGoing = True if socket: wordCount() else: g_exportedScripts = wordCount, # # # characters counting feature added (C) 2010, Jan Jełowicki # jj # # Disclaimer and license from acb's macros # # Standard disclaimer and MIT licence . # These macros are copyright (c) 2003-4 Andrew Brown. # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the 'Software'), to deal in the Software without # restriction, including without limitation the rights to use, copy, # modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE.