class DaemonTrayIconMixin(object): '''Mixin class for using the tray icon in combination with the background process. Sub classes should run as a separate child process. ''' def __init__(self): self.server = ServerProxy() def main(self): # Set window icon in case we open the notebook dialog gtk_window_set_default_icon() gtk.main() def quit(self): gtk.main_quit() def list_open_notebooks(self): for uri in self.server.list_notebooks(): info = NotebookInfo(uri) info.active = True yield info def do_activate_notebook(self, uri): self.server.get_notebook(uri).toggle_present() def do_quit(self): self.server.quit()
def __init__(self, plugin, window): WindowExtension.__init__(self, plugin, window) self.window.ui.hideonclose = True # XXX self.proxyobject = None obj = RemoteObject('zim.plugins.trayicon.' + self.trayiconclass.__name__) server = ServerProxy() self.proxyobject = server.get_proxy(obj)
def connect_trayicon(self): klass = self.get_trayicon_class() if issubclass(klass, DaemonTrayIconMixin): obj = RemoteObject('zim.plugins.trayicon.' + klass.__name__) server = ServerProxy() self.proxyobject = server.get_proxy(obj) # getting the object implicitly starts it, if it didn't exist yet else: self.icon = klass(self.ui) self._trayicon_class = klass
def main(*args): start_server_if_not_running() preferences = get_config('preferences.conf')['TrayIconPlugin'] preferences.setdefault('classic', False) if appindicator and not preferences['classic']: obj = RemoteObject('zim.plugins.trayicon.AppIndicatorTrayIcon') else: obj = RemoteObject('zim.plugins.trayicon.DaemonTrayIcon') server = ServerProxy() if not server.has_object(obj): server.init_object(obj)
def _get_ui(self): start_server_if_not_running() notebook = self.notebookcombobox.get_notebook() if notebook: return ServerProxy().get_notebook(notebook) else: return None
def run(self): start_server_if_not_running() config = ConfigManager() preferences = config.get_config_dict( 'preferences.conf')['TrayIconPlugin'] preferences.setdefault('classic', False) if appindicator and not preferences['classic']: obj = RemoteObject('zim.plugins.trayicon.AppIndicatorTrayIcon') else: obj = RemoteObject('zim.plugins.trayicon.DaemonTrayIcon') server = ServerProxy() if not server.has_object(obj): server.init_object(obj)
def main(self): ServerProxy().connect('notebook-list-changed', self) self.on_notebook_list_changed() DaemonTrayIconMixin.main(self)
def __init__(self): self.server = ServerProxy()
def run(self): if not self.opts or self.opts.get('help'): print usagehelp else: _raise = 'raise' in self.opts _show = 'show' in self.opts if 'notebook' in self.opts: notebookInfo = resolve_notebook(self.opts['notebook']) else: notebookInfo = resolve_notebook(defaultNotebook) print 'NotebookInfo=', notebookInfo # The notion of 'today' might extend into the wee hours of the morning. offset_time = datetime.today() - timedelta( hours=hours_past_midnight) todaysJournal = offset_time.strftime(':Journal:%Y:%m:%d') if 'page' in self.opts: pagename = self.opts['page'] elif 'journal' in self.opts: pagename = todaysJournal elif 'date' in self.opts: pagename = parse( self.opts['date']).strftime(':Journal:%Y:%m:%d') else: print self.opts raise Exception, 'you must somehow identify a page to modify' print 'Pagename=', pagename ui = None notebook = None if (zim66): server = ZIM_APPLICATION #print ZIM_APPLICATION._running for window in ZIM_APPLICATION._windows: if window.ui.notebook.uri == notebookInfo.uri: notebook = window.ui.notebook ui = window.ui break else: logger.debug("not it: '%s' != '%s'", window.ui.notebook.uri, notebookInfo.uri) else: start_server_if_not_running() server = ServerProxy() pprint.pprint(server.list_objects()) ui = server.get_notebook(notebookInfo, _raise or _show) notebook = ui.notebook print 'Server=', server print 'UI=', ui print 'Notebook?=', notebook quoting = ('quote' in self.opts) text = '' emptyString = False if 'literal' in self.opts: if type(self.opts['literal']) == bool: emptyString = True else: text += self.opts['literal'] if 'time' in self.opts: print "time(): ", time.time() print "timezone: ", time.tzname print "localtime: ", time.localtime() if pagename == todaysJournal: # It's log-like... all the same day... so don't include the full date... text = strftime('%I:%M%P - ') + text else: text = strftime('%Y-%m-%d @ %I:%M%P - ') + text if 'file' in self.opts: #if not quoting: # text += '\n{0}:\n'.format(self.opts['file']) text += open(self.opts['file']).read() if 'clipboard' in self.opts: text += SelectionClipboard.get_text() or Clipboard.get_text() # BUG: This does not work, because this code executes in the main zim process... # we need a pre-handoff hook to convert it to a '--literal', or similar. if 'stdin' in self.opts: import sys text += sys.stdin.read() # -------------------------------------------------------------------------------- if text and quoting: text = "'''\n{0}\n'''".format(text) didSomething = False if text or emptyString: # BUG: the journal template is not used for new pages... # BUG: If the page does not exist, then we assume that it cannot be 'open'... while generally true, this is probably technically incorrect for stub pages just-navigated-to (but not yet saved). if self.pageExists(notebookInfo, pagename): print 'Page exists...' if 'create' in self.opts: raise Exception, 'Page already exists: ' + pagename if ui is None: self._direct_append(notebookInfo, pagename, text) else: ui.append_text_to_page(pagename, text) elif ui is None: self._direct_create(notebookInfo, pagename, text) elif self.likelyHasChildPages(ui, notebookInfo, pagename): print 'Page dne, but has children... yuck...' # The new_page_from_text function would create enumerated side-pages... # so we can't use the template when creating a new page... :-( #text = ( # "====== " + pagename + " ======\n" # "https://github.com/Osndok/zim-plugin-append/issues/1\n\n" # +text #) #ui.append_text_to_page(pagename, text); path = ui.notebook.pages.lookup_from_user_input(pagename) page = ui.notebook.get_page( path) # as opposed to 'get_new_page' (!!!!) parsetree = ui.notebook.get_template(page) page.set_parsetree(parsetree) page.parse('wiki', text, append=True) # FIXME format hard coded ui.notebook.store_page(page) else: print 'Page does not exist' if 'exists' in self.opts: raise Exception, 'Page does not exist: ' + pagename ui.new_page_from_text(text, name=pagename, use_template=True) didSomething = True #BUG: these features don't work without 'ui'... if 'directory' in self.opts: ui.import_attachments(path, self.opts['directory']) didSomething = True if 'attach' in self.opts: if zim66: attachments = notebook.get_attachments_dir(path) file = dir.file(name) if file.isdir(): print 'BUG: dont know how to handle folders in 0.66' else: file.copyto(attachments) else: ui.do_attach_file(path, self.opts['attach']) if _raise or _show: if ui: ui.present(pagename) didSomething = True else: print 'ERROR: unable to raise/show window, no UI running'
def main(argv): """Run the main program Depending on the commandline given and whether or not there is an instance of zim running already, this method may return immediatly, or go into the mainloop untill the program is exitted. @param argv: commandline arguments, e.g. from C{sys.argv} @raises UsageError: when number of arguments is not correct @raises GetOptError: when invalid options are found """ global ZIM_EXECUTABLE # FIXME - this returns python.exe on my windows test ZIM_EXECUTABLE = argv[0] zim_exec_file = File(ZIM_EXECUTABLE) if zim_exec_file.exists(): # We were given an absolute path, e.g. "python ./zim.py" ZIM_EXECUTABLE = zim_exec_file.path # Check for special commandline args for ipc, does not return # if handled import zim.ipc zim.ipc.handle_argv() # Let getopt parse the option list short = "".join(shortopts.keys()) for s, l in shortopts.items(): if l.endswith("="): short = short.replace(s, s + ":") long = list(longopts) + list(commands) for opts in commandopts.values(): long.extend(opts) opts, args = gnu_getopt(argv[1:], short, long) # First figure out which command to execute cmd = "gui" # default if opts: o = opts[0][0].lstrip("-") if o in shortopts: o = shortopts[o].rstrip("=") if o in commands: opts.pop(0) cmd = o # If it is a simple command execute it and return if cmd == "version": print "zim %s\n" % __version__ print __copyright__, "\n" print __license__ return elif cmd == "help": print usagehelp.replace("zim", argv[0]) print optionhelp return # Otherwise check the number of arguments if cmd in maxargs and len(args) > maxargs[cmd]: raise UsageError # --manual is an alias for --gui /usr/share/zim/manual if cmd == "manual": cmd = "gui" args.insert(0, data_dir("manual").path) # Now figure out which options are allowed for this command allowedopts = list(longopts) allowedopts.extend(commandopts[cmd]) # Convert options into a proper dict optsdict = {} for o, a in opts: o = str(o.lstrip("-")) # str() -> no unicode for keys if o in shortopts: o = shortopts[o].rstrip("=") if o + "=" in allowedopts: o = o.replace("-", "_") optsdict[o] = a elif o in allowedopts: o = o.replace("-", "_") optsdict[o] = True else: raise GetoptError, ("--%s is not allowed in combination with --%s" % (o, cmd), o) # --port is the only option that is not of type string if "port" in optsdict and not optsdict["port"] is None: try: optsdict["port"] = int(optsdict["port"]) except ValueError: raise GetoptError, ("--port takes an integer argument", "port") # set logging output level for logging root (format has been set in zim.py) if not ZIM_EXECUTABLE[-4:].lower() == ".exe": # for most platforms level = logging.WARN else: # if running from Windows compiled .exe level = logging.ERROR if optsdict.pop("verbose", False): level = logging.INFO if optsdict.pop("debug", False): level = logging.DEBUG # no "elif" ! logging.getLogger().setLevel(level) logger.info("This is zim %s", __version__) if level == logging.DEBUG: logger.debug("Python version is %s", str(sys.version_info)) logger.debug("Platform is %s", os.name) logger.debug(get_zim_revision()) log_basedirs() # Now we determine the class to handle this command # and start the application ... logger.debug("Running command: %s", cmd) if cmd in ("export", "index", "search"): if not len(args) >= 1: default = _get_default_or_only_notebook() if not default: raise UsageError handler = NotebookInterface(notebook=default) else: handler = NotebookInterface(notebook=args[0]) handler.load_plugins() # should this go somewhere else ? if cmd == "search": if not len(args) == 2: raise UsageError optsdict["query"] = args[1] elif len(args) == 2: optsdict["page"] = args[1] method = getattr(handler, "cmd_" + cmd) method(**optsdict) elif cmd == "gui": notebook = None page = None if args: from zim.notebook import resolve_notebook notebook, page = resolve_notebook(args[0]) if not notebook: notebook = File(args[0]).uri # make sure daemon approves of this uri and proper # error dialog is shown as a result by GtkInterface if len(args) == 2: page = args[1] if "list" in optsdict: del optsdict["list"] # do not use default elif not notebook: import zim.notebook default = _get_default_or_only_notebook() if default: notebook = default logger.info("Opening default notebook") # DGT: HACK for debuger if "standalone" in optsdict or DEBUG: import zim.gui try: del optsdict["standalone"] except: pass if not notebook: import zim.gui.notebookdialog notebook = zim.gui.notebookdialog.prompt_notebook() if not notebook: return # User canceled notebook dialog handler = zim.gui.GtkInterface(notebook, page, **optsdict) handler.main() else: from zim.ipc import start_server_if_not_running, ServerProxy if not notebook: import zim.gui.notebookdialog notebook = zim.gui.notebookdialog.prompt_notebook() if not notebook: return # User canceled notebook dialog start_server_if_not_running() server = ServerProxy() gui = server.get_notebook(notebook) gui.present(page, **optsdict) logger.debug( """ NOTE FOR BUG REPORTS: At this point zim has send the command to open a notebook to a background process and the current process will now quit. If this is the end of your debug output it is probably not useful for bug reports. Please close all zim windows, quit the zim trayicon (if any), and try again. """ ) elif cmd == "server": standalone = optsdict.pop("standalone", False) # No daemon support for server, so no option doesn't # do anything for now gui = optsdict.pop("gui", False) if gui: import zim.gui.server zim.gui.server.main(*args, **optsdict) else: import zim.www zim.www.main(*args, **optsdict) elif cmd == "plugin": import zim.plugins try: pluginname = args.pop(0) except IndexError: raise UsageError module = zim.plugins.get_plugin_module(pluginname) module.main(*args)