def testUrlHelper(self): systemPath = os.getcwd() if systemPath.startswith("/"): self.failUnless("/tmp" == unohelper.fileUrlToSystemPath("file:///tmp")) self.failUnless("file:///tmp" == unohelper.systemPathToFileUrl("/tmp")) else: self.failUnless("c:\\temp" == unohelper.fileUrlToSystemPath("file:///c:/temp")) self.failUnless("file:///c:/temp" == unohelper.systemPathToFileUrl("c:\\temp")) systemPath = unohelper.systemPathToFileUrl(systemPath) self.failUnless(systemPath + "/a" == unohelper.absolutize(systemPath, "a"))
def testUrlHelper( self ): systemPath = os.getcwd() if systemPath.startswith( "/" ): self.failUnless( "/tmp" == unohelper.fileUrlToSystemPath( "file:///tmp" ) ) self.failUnless( "file:///tmp" == unohelper.systemPathToFileUrl( "/tmp" )) else: self.failUnless( "c:\\temp" == unohelper.fileUrlToSystemPath( "file:///c:/temp" ) ) self.failUnless( "file:///c:/temp" == unohelper.systemPathToFileUrl( "c:\\temp" ) ) systemPath = unohelper.systemPathToFileUrl( systemPath ) self.failUnless( systemPath + "/a" == unohelper.absolutize( systemPath, "a" ) )
def checkForPythonPathBesideScript(url): if url.startswith("file:"): path = unohelper.fileUrlToSystemPath(url + "/pythonpath.zip") log.debug("checking for existence of {}", path) if os.access(encfile(path), os.F_OK) and not path in sys.path: log.debug("adding {} to sys.path", path) sys.path.append(path) path = unohelper.fileUrlToSystemPath(url + "/pythonpath") log.debug("checking for existence of {}", path) if os.access(encfile(path), os.F_OK) and not path in sys.path: log.debug("adding {} to sys.path", path) sys.path.append(path)
def checkForPythonPathBesideScript( url ): if url.startswith( "file:" ): path = unohelper.fileUrlToSystemPath( url+"/pythonpath.zip" ); log.log( LogLevel.DEBUG, "checking for existence of " + path ) if 1 == os.access( encfile(path), os.F_OK) and not path in sys.path: log.log( LogLevel.DEBUG, "adding " + path + " to sys.path" ) sys.path.append( path ) path = unohelper.fileUrlToSystemPath( url+"/pythonpath" ); log.log( LogLevel.DEBUG, "checking for existence of " + path ) if 1 == os.access( encfile(path), os.F_OK) and not path in sys.path: log.log( LogLevel.DEBUG, "adding " + path + " to sys.path" ) sys.path.append( path )
def checkForPythonPathBesideScript(url): if url.startswith("file:"): path = unohelper.fileUrlToSystemPath(url + "/pythonpath.zip") log.log(LogLevel.DEBUG, "checking for existence of " + path) if 1 == os.access(encfile(path), os.F_OK) and not path in sys.path: log.log(LogLevel.DEBUG, "adding " + path + " to sys.path") sys.path.append(path) path = unohelper.fileUrlToSystemPath(url + "/pythonpath") log.log(LogLevel.DEBUG, "checking for existence of " + path) if 1 == os.access(encfile(path), os.F_OK) and not path in sys.path: log.log(LogLevel.DEBUG, "adding " + path + " to sys.path") sys.path.append(path)
def checkForPythonPathBesideComponent( url ): path = unohelper.fileUrlToSystemPath( url+"/pythonpath.zip" ); if DEBUG == 1: print "checking for existence of " + encfile( path ) if 1 == os.access( encfile( path ), os.F_OK) and not path in sys.path: if DEBUG == 1: print "adding " + encfile( path ) + " to sys.path" sys.path.append( path ) path = unohelper.fileUrlToSystemPath( url+"/pythonpath" ); if 1 == os.access( encfile( path ), os.F_OK) and not path in sys.path: if DEBUG == 1: print "adding " + encfile( path ) + " to sys.path" sys.path.append( path )
def checkForPythonPathBesideComponent(url): path = unohelper.fileUrlToSystemPath(url + "/pythonpath.zip") if DEBUG == 1: print(b"checking for existence of " + encfile(path)) if 1 == os.access(encfile(path), os.F_OK) and not path in sys.path: if DEBUG == 1: print(b"adding " + encfile(path) + b" to sys.path") sys.path.append(path) path = unohelper.fileUrlToSystemPath(url + "/pythonpath") if 1 == os.access(encfile(path), os.F_OK) and not path in sys.path: if DEBUG == 1: print(b"adding " + encfile(path) + b" to sys.path") sys.path.append(path)
def export_web_data(self): '''Pick a directory,then export web settings''' self.dialog.execute() folder = self.dialog.getDirectory() if folder: from shutil import copy import os.path from unohelper import fileUrlToSystemPath from settings import save_file_name from messagebox import BUTTONS_OK_CANCEL, WARNINGBOX, INFOBOX folder_url = fileUrlToSystemPath(folder) file = os.path.join(folder_url, save_file_name) try: if os.path.isfile(file): answer = self.msg_box.show("The file exists, replace?", "Warning", WARNINGBOX, BUTTONS_OK_CANCEL) if answer: copy(self.move_from, folder_url) self.msg_box.show("Web settings exported successfully", "Message", INFOBOX) else: copy(self.move_from, folder_url) self.msg_box.show("Web settings exported successfully", "Message", INFOBOX) except OSError as error: if error.errno == 13: self.msg_box.show("You have no rights to save here file ", "Attention", WARNINGBOX)
def actionPerformed(self, actionevent): cmd = actionevent.ActionCommand if cmd == "filepick": systempath = self.editcontrol.getText().strip( ) # Editコントロールのテキストを取得。システム固有形式のパスが入っているはず。 if os.path.exists(systempath): # パスが実存するとき if os.path.isfile(systempath): # ファイルへのパスであればその親フォルダのパスを取得する。 systempath = os.path.dirname(systempath) fileurl = unohelper.systemPathToFileUrl( systempath) # fileurlに変換する。 else: fileurl = self.workurl # 実存するパスが取得できない時はホームフォルダのfileurlを取得。 self.filepicker.setDisplayDirectory( fileurl) # 表示するフォルダを設定。設定しないと「最近開いたファイル」が表示される。 if self.filepicker.execute( ) == ExecutableDialogResults_OK: # ファイル選択ダイアログを表示し、そのOKボタンがクリックされた時。 fileurl = self.filepicker.getFiles()[ 0] # ダイアログで選択されたファイルのパスを取得。fileurlのタプルで返ってくるので先頭の要素を取得。 if self.simplefileaccess.exists(fileurl): # fileurlが実存するとき self.imagecontrolmodel.setPropertyValue( "ImageURL", fileurl) # Imageコントロールに設定。 systempath = unohelper.fileUrlToSystemPath( fileurl) # fileurlをシステム固有形式に変換。 self.editcontrol.setText(systempath) # Editコントロールに表示。 elif cmd == "close": self.frame.close(True)
def import_web_data(self): '''Shows the dialog ,pick a file, then import entire file.''' self.dialog.execute() file = self.dialog.getSelectedFiles() if file: from shutil import copyfile import os.path from unohelper import fileUrlToSystemPath from messagebox import BUTTONS_OK_CANCEL, WARNINGBOX, INFOBOX file_url = fileUrlToSystemPath(file[0]) try: if os.path.isfile(self.destination): answer = self.msg_box.show("The file exists, replace?", "Warning", WARNINGBOX, BUTTONS_OK_CANCEL) if answer: copyfile(file_url, self.destination) self.msg_box.show("Web settings imported successfully", "Message", INFOBOX) except OSError as error: if error.errno == 13: self.msg_box.show( "You have no rights to create settings file", "Attention", WARNINGBOX)
def actionPerformed(self, actionevent): cmd = actionevent.ActionCommand ctx, smgr, configurationprovider, css, properties, nodepath, simplefileaccess = self.consts dialog = self.dialog if cmd=="folderpicker": fixedtext = dialog.getControl("RefDir") path = fixedtext.getText() # システムパスが返ってくる。 folderpicker = smgr.createInstanceWithContext("com.sun.star.ui.dialogs.FolderPicker", ctx) if os.path.exists(path): # pathが存在するとき fileurl = unohelper.systemPathToFileUrl(path) # システムパスをfileurlに変換する。 folderpicker.setDisplayDirectory(fileurl) # フォルダ選択ダイアログに設定する。 folderpicker.setTitle(_("Select ref folder")) if folderpicker.execute()==OK: fileurl = folderpicker.getDirectory() checkbox = dialog.getControl("OffLine") if simplefileaccess.exists(fileurl): path = unohelper.fileUrlToSystemPath(fileurl) # fileurlをシステムパスに変換する。 checkbox.setEnable(True) else: path = "Local API Reference does not exists." checkbox.setEnable(False) fixedtext.setText(path) elif cmd=="restore": node = PropertyValue(Name="nodepath", Value="{}Defaults".format(nodepath)) root = configurationprovider.createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess", (node,)) configs = root.getPropertyValues(properties) # コンポーネントデータノードからデフォルト値を取得する。 toControls(dialog, toDialog(ctx, smgr, css, simplefileaccess, configs)) # 各コントロールに値を入力する。
def createKeikaPathname(doc, transliteration, idtxt, kanatxt, filename): kanatxt = convertKanaFULLWIDTH(transliteration, kanatxt) # カナ名を半角からスペースを削除して全角にする。 dirpath = os.path.dirname(unohelper.fileUrlToSystemPath( doc.getURL())) # このドキュメントのあるディレクトリのフルパスを取得。 return os.path.join(dirpath, "*", filename.format(kanatxt, idtxt)) # ワイルドカード入のシートファイル名を取得。
def initpath(self): path = self.config.Origin expander = self.ctx.getValueByName( '/singletons/com.sun.star.util.theMacroExpander') path = expander.expandMacros(path) path = path[len('vnd.sun.star.expand:'):] path = unohelper.absolutize(os.getcwd(), path) path = unohelper.fileUrlToSystemPath(path) self.path = path
def toDialog(ctx, smgr, css, simplefileaccess, configs): # ダイアログ向けにデータを変換する。 offline, refurl, refdir, idlstext = configs # コンポーネントデータノード用の値を取得。 state = 1 if offline else 0 pathsubstservice = smgr.createInstanceWithContext("com.sun.star.comp.framework.PathSubstitution", ctx) fileurl = pathsubstservice.substituteVariables(refdir, True) # $(inst)を変換する。fileurlが返ってくる。 path = os.path.normpath(unohelper.fileUrlToSystemPath(fileurl)) if simplefileaccess.exists(fileurl) else "Local API Reference does not exists." # fileurlをシステムパスに変換する。パスの実存を確認する。 idls = "".join(idlstext.split()).split(",") # xmlがフォーマットされていると空白やタブが入ってくるのでそれを除去してリストにする。 idlsedit = ", ".join("{}{}".format(css, i) if i.startswith(".") else i for i in idls) return state, refurl, path, idlsedit
def _get_dir_path(ctx, title="Choose directory", default_dir=None): dp = ctx.getServiceManager().createInstanceWithContext( "com.sun.star.ui.dialogs.FolderPicker", ctx) if default_dir: dp.setDisplayDirectory(default_dir) if dp.execute(): return unohelper.fileUrlToSystemPath(dp.getDirectory()) else: return
def initpath( self ): path = self.config.Origin expander = self.ctx.getValueByName( '/singletons/com.sun.star.util.theMacroExpander' ) path = expander.expandMacros( path ) path = path[len( 'vnd.sun.star.expand:' ):] import os path = unohelper.absolutize( os.getcwd(), path ) path = unohelper.fileUrlToSystemPath( path ) self.path = path
def getpath( ctx, classname ): config = getconfig( ctx, 'org.openoffice.eoec.%sSettings/ConfigNode'%classname ) path = config.Origin expander = ctx.getValueByName( '/singletons/com.sun.star.util.theMacroExpander' ) path = expander.expandMacros( path ) path = path[len( 'vnd.sun.star.expand:' ):] import os path = unohelper.absolutize( os.getcwd(), path ) path = unohelper.fileUrlToSystemPath( path ) return path
def macro(): ctx = XSCRIPTCONTEXT.getComponentContext() # コンポーネントコンテクストの取得。 smgr = ctx.getServiceManager() # サービスマネージャーの取得。 doc = XSCRIPTCONTEXT.getDocument() # マクロを起動した時のドキュメントのモデルを取得。 docframe = doc.getCurrentController().getFrame() # モデル→コントローラ→フレーム、でドキュメントのフレームを取得。 docwindow = docframe.getContainerWindow() # ドキュメントのウィンドウ(コンテナウィンドウ=ピア)を取得。 toolkit = docwindow.getToolkit() # ピアからツールキットを取得。 taskcreator = smgr.createInstanceWithContext('com.sun.star.frame.TaskCreator', ctx) args = NamedValue("PosSize", Rectangle(100, 100, 530, 290)), NamedValue("FrameName", "ImageControlSample") # , NamedValue("MakeVisible", True) # TaskCreatorで作成するフレームのコンテナウィンドウのプロパティ。 frame = taskcreator.createInstanceWithArguments(args) # コンテナウィンドウ付きの新しいフレームの取得。 window = frame.getContainerWindow() # 新しいコンテナウィンドウを新しいフレームから取得。 frame.setTitle("Image Viewer") # フレームのタイトルを設定。 docframe.getFrames().append(frame) # 新しく作ったフレームを既存のフレームの階層に追加する。 actionlistener = ActionListener(ctx, smgr, frame) # ボタンにつけるリスナー。コントロールコンテナはコントロールが追加されてから取得する。 margin_horizontal = 20 # 水平マージン margin_vertical = 13 # 垂直マージン window_width = 537 # ウィンドウ幅 window_height = 287 # ウィンドウの高さ line_height = 23 # Editコントロールやボタンコントロールなどの高さ buttonfilepick_width = 56 # ButtonFilePickボタンの幅。 buttonclose_width = 90 # ButtonCloseボタンの幅。 radiobutton_width = 120 # RadioButtonの幅。 datalabel_width = 200 # FixedText2、FixedText3の幅。 minwidth = margin_horizontal*2+radiobutton_width+buttonfilepick_width+5 # Edit1の幅>=1を幅の下限値とする。 minheight = margin_vertical*5+line_height*2+1 # ImageControlの高さ>=1を高さの下限値とする。 minsizes = minwidth, minheight # コントロールが潰れてしまうと次のリサイズの計算がおかしくなるので下限値を設定する。 editcontrol_Y = window_height-(margin_vertical+line_height)*2 # Edit1のY。頻用値を取得しておく。 imagecontrolmargins = margin_horizontal*2, margin_vertical*5+line_height*2 # ウィンドウサイズの幅高さ-イメージコントロールの幅高さを取得。 itemlistener = ItemListener(toolkit, window, imagecontrolmargins) pathsubstservice = smgr.createInstanceWithContext("com.sun.star.comp.framework.PathSubstitution", ctx) uno_path = pathsubstservice.getSubstituteVariableValue("$(prog)") # fileurlでprogramフォルダへのパスが返ってくる。 fileurl = "{}/intro.png".format(uno_path) # 画像ファイルへのfileurl imageurl = os.path.normpath(unohelper.fileUrlToSystemPath(fileurl)) # fileurlをシステム固有のパスに変換して正規化する。 controlcontainer, addControl = controlcontainerCreator(ctx, smgr, {"PositionX": 0, "PositionY": 0, "Width": window_width, "Height": window_height, "BackgroundColor": 0xF0F0F0, "PosSize": POSSIZE}) # ウィンドウに表示させるコントロールコンテナを取得。BackgroundColor: -1は不可。 imagecontrol1 = addControl("ImageControl", {"PositionX": margin_horizontal, "PositionY": margin_vertical, "Width": window_width-margin_horizontal*2, "Height": window_height-margin_vertical*5-line_height*2, "Border": 0, "ScaleImage": True, "ScaleMode": ISOTROPIC, "ImageURL": fileurl, "PosSize": POSSIZE}) edit1 = addControl("Edit", {"PositionX": margin_horizontal+radiobutton_width+2, "PositionY": editcontrol_Y, "Width": window_width-margin_horizontal*2-radiobutton_width-buttonfilepick_width-4, "Height": line_height, "Text": imageurl, "PosSize": POSSIZE}) button1 = addControl("Button", {"PositionX": window_width-margin_horizontal-buttonfilepick_width, "PositionY": editcontrol_Y, "Width": buttonfilepick_width, "Height": line_height, "Label": "~Browse", "PosSize": POSSIZE}, {"setActionCommand": "filepick" ,"addActionListener": actionlistener}) # PushButtonTypeは動かない。 radiobutton1 = addControl("RadioButton", {"PositionX": margin_horizontal, "PositionY": editcontrol_Y, "Width": radiobutton_width, "Height": line_height, "Label": "~No Scaling", "PosSize": POSSIZE}, {"addItemListener": itemlistener}) radiobutton2 = addControl("RadioButton", {"PositionX": margin_horizontal, "PositionY": editcontrol_Y+line_height+int((margin_vertical*2-line_height)/3), "Width": radiobutton_width, "Height": line_height, "Label": "~ISOTROPIC", "State": 1, "PosSize": POSSIZE}, {"addItemListener": itemlistener}) radiobutton3 = addControl("RadioButton", {"PositionX": margin_horizontal, "PositionY": editcontrol_Y+(line_height+int((margin_vertical*2-line_height)/3))*2, "Width": radiobutton_width, "Height": line_height, "Label": "~ANISOTROPIC", "PosSize": POSSIZE}, {"addItemListener": itemlistener}) imagecontrolrectangle = imagecontrol1.getPosSize() graphic = imagecontrol1.getModel().getPropertyValue("Graphic") # イメージコントロールの画像を取得。 graphicrectangle = graphic.getPropertyValue("SizePixel") # 画像のオリジナルの大きさを取得。 fixedtext1 = addControl("FixedText", {"PositionX": margin_horizontal+radiobutton_width+2, "PositionY": editcontrol_Y+line_height+int((margin_vertical*2-line_height)/3), "Width": datalabel_width, "Height": line_height, "Label": "{} x {} px Image Size".format(graphicrectangle.Width, graphicrectangle.Height), "VerticalAlign": MIDDLE, "PosSize": POSSIZE}) # デフォルトでは"VerticalAlign": TOP、になっている。 fixedtext2 = addControl("FixedText", {"PositionX": margin_horizontal+radiobutton_width+2, "PositionY": editcontrol_Y+(line_height+int((margin_vertical*2-line_height)/3))*2, "Width": datalabel_width, "Height": line_height, "Label": "{} x {} px Display Size".format(imagecontrolrectangle.Width, imagecontrolrectangle.Height), "VerticalAlign": MIDDLE, "PosSize": POSSIZE}) button2 = addControl("Button", {"PositionX": window_width-margin_horizontal-buttonclose_width, "PositionY": window_height-margin_vertical-line_height, "Width": buttonclose_width, "Height": line_height, "Label": "~Close dialog", "PosSize": POSSIZE}, {"setActionCommand": "close" ,"addActionListener": actionlistener}) # PushButtonTypeは動かない。 actionlistener.setControl(imagecontrol1, edit1, fixedtext1) # getControl()で追加するコントロールが追加されてからコントロールコンテナを取得する。 radiobuttons = radiobutton1, radiobutton2, radiobutton3 itemlistener.setControl(imagecontrol1, radiobuttons) controlcontainer.createPeer(toolkit, window) # ウィンドウにコントロールを描画。 controlcontainer.setVisible(True) # コントロールの表示。 window.setVisible(True) # ウィンドウの表示 controls = controlcontainer, imagecontrol1, edit1, button1, button2, radiobutton1, radiobutton2, radiobutton3, fixedtext1, fixedtext2 window.addWindowListener(WindowListener(controls, minsizes)) # setVisible(True)でも呼び出されるので、その後でリスナーを追加する。
def trigger(self, args): try: gdoc = self.desktop.getCurrentComponent() if gdoc and gdoc.URL in PLUGIN.documents: doc = PLUGIN.documents[gdoc.URL]["openplm_doc"] doc_file_id = PLUGIN.documents[gdoc.URL]["openplm_file_id"] path = PLUGIN.documents[gdoc.URL]["openplm_path"] if not doc or not PLUGIN.check_is_locked( doc["id"], doc_file_id): return revisable = PLUGIN.get_data("api/object/%s/isrevisable/" % doc["id"])["revisable"] if not revisable: win = gdoc.CurrentController.Frame.ContainerWindow show_error("Document can not be revised", win) return res = PLUGIN.get_data("api/object/%s/nextrevision/" % doc["id"]) revision = res["revision"] name = os.path.basename(path) dialog = ReviseDialog(self.ctx, doc, name, revision) dialog.run() if gdoc.URL not in PLUGIN.documents: path = unohelper.fileUrlToSystemPath(gdoc.URL) close(gdoc, self.desktop) try: os.remove(path) except os.error: pass if dialog.gdoc and dialog.gdoc.URL not in PLUGIN.documents: path = unohelper.fileUrlToSystemPath(dialog.gdoc.URL) close(dialog.gdoc, self.desktop) try: os.remove(path) except os.error: pass else: win = gdoc.CurrentController.Frame.ContainerWindow show_error("Document not stored in OpenPLM", win) except: traceback.print_exc()
def get_save_dir(ctx): '''Returns the save file directory, if don't exists, it will be created''' from settings import save_dir_name import unohelper import os _path = ctx.ServiceManager.createInstance("com.sun.star.util.PathSubstitution") user_dir = _path.getSubstituteVariableValue("$(user)") user_dir = unohelper.fileUrlToSystemPath(user_dir) save_dir = os.path.join(user_dir, save_dir_name) if save_dir_name not in os.listdir(user_dir): os.mkdir(save_dir) return save_dir
def trigger(self, args): try: gdoc = self.desktop.getCurrentComponent() if gdoc and gdoc.URL in PLUGIN.documents: doc = PLUGIN.documents[gdoc.URL]["openplm_doc"] doc_file_id = PLUGIN.documents[gdoc.URL]["openplm_file_id"] path = PLUGIN.documents[gdoc.URL]["openplm_path"] if not doc or not PLUGIN.check_is_locked(doc["id"], doc_file_id): return revisable = PLUGIN.get_data("api/object/%s/isrevisable/" % doc["id"])["revisable"] if not revisable: win = gdoc.CurrentController.Frame.ContainerWindow show_error("Document can not be revised", win) return res = PLUGIN.get_data("api/object/%s/nextrevision/" % doc["id"]) revision = res["revision"] name = os.path.basename(path) dialog = ReviseDialog(self.ctx, doc, name, revision) dialog.run() if gdoc.URL not in PLUGIN.documents: path = unohelper.fileUrlToSystemPath(gdoc.URL) close(gdoc, self.desktop) try: os.remove(path) except os.error: pass if dialog.gdoc and dialog.gdoc.URL not in PLUGIN.documents: path = unohelper.fileUrlToSystemPath(dialog.gdoc.URL) close(dialog.gdoc, self.desktop) try: os.remove(path) except os.error: pass else: win = gdoc.CurrentController.Frame.ContainerWindow show_error("Document not stored in OpenPLM", win) except: traceback.print_exc()
def createHtml(ctx, offline, outputs): # ウェブブラウザに出力。 outputs.append("</code>") html = "<br/>".join(outputs).replace(" ", chr(0x00A0)) # 半角スペースをノーブレークスペースに置換する。 html = re.sub(r'(?<!\u00A0)\u00A0(?!\u00A0)', " ", html) # タグ内にノーブレークスペースはエラーになるので連続しないノーブレークスペースを半角スペースに戻す。 title = "TCU - Tree Command for UNO" if offline: # ローカルリファレンスを使うときはブラウザのセキュリティの制限のためにhtmlファイルを開くようにしないとローカルファイルが開けない。 pathsettingssingleton = ctx.getByName('/singletons/com.sun.star.util.thePathSettings') fileurl = pathsettingssingleton.getPropertyValue("Temp") systempath = unohelper.fileUrlToSystemPath(fileurl) filepath = os.path.join(systempath, "tcu_output.html") createHTMLfile(filepath, title, html) else: server = Wsgi(title, html) server.wsgiServer()
def getModuleFromUrl(self, url): if DEBUG: print("pythonloader: interpreting url " + url) protocol, dependent = splitUrl(url) if "vnd.sun.star.expand" == protocol: exp = self.ctx.getValueByName( "/singletons/com.sun.star.util.theMacroExpander") url = exp.expandMacros(dependent) protocol, dependent = splitUrl(url) if DEBUG: print("pythonloader: after expansion " + protocol + ":" + dependent) try: if "file" == protocol: # remove \..\ sequence, which may be useful e.g. in the build env url = unohelper.absolutize(url, url) # did we load the module already ? mod = g_loadedComponents.get(url) if not mod: mod = imp.new_module("uno_component") # check for pythonpath.zip beside .py files checkForPythonPathBesideComponent(url[0:url.rfind('/')]) # read the file filename = unohelper.fileUrlToSystemPath(url) fileHandle = file(filename) src = fileHandle.read().replace("\r", "") if not src.endswith("\n"): src = src + "\n" # compile and execute the module codeobject = compile(src, encfile(filename), "exec") exec(codeobject, mod.__dict__) mod.__file__ = encfile(filename) g_loadedComponents[url] = mod return mod elif "vnd.openoffice.pymodule" == protocol: return __import__(dependent) else: raise RuntimeException( "PythonLoader: Unknown protocol " + protocol + " in url " + url, self) except ImportError as e: raise RuntimeException( "Couldn't load " + url + " for reason " + str(e), None) return None
def getModuleFromUrl( self, url ): if DEBUG: print("pythonloader: interpreting url " +url) protocol, dependent = splitUrl( url ) if "vnd.sun.star.expand" == protocol: exp = self.ctx.getValueByName( "/singletons/com.sun.star.util.theMacroExpander" ) url = exp.expandMacros(dependent) protocol,dependent = splitUrl( url ) if DEBUG: print("pythonloader: after expansion " +protocol +":" + dependent) try: if "file" == protocol: # remove \..\ sequence, which may be useful e.g. in the build env url = unohelper.absolutize( url, url ) # did we load the module already ? mod = g_loadedComponents.get( url ) if not mod: mod = imp.new_module("uno_component") # check for pythonpath.zip beside .py files checkForPythonPathBesideComponent( url[0:url.rfind('/')] ) # read the file filename = unohelper.fileUrlToSystemPath( url ) fileHandle = file( filename ) src = fileHandle.read().replace("\r","") if not src.endswith( "\n" ): src = src + "\n" # compile and execute the module codeobject = compile( src, encfile(filename), "exec" ) exec(codeobject, mod.__dict__) mod.__file__ = encfile(filename) g_loadedComponents[url] = mod return mod elif "vnd.openoffice.pymodule" == protocol: return __import__( dependent ) else: raise RuntimeException( "PythonLoader: Unknown protocol " + protocol + " in url " +url, self ) except ImportError as e: raise RuntimeException( "Couldn't load "+url+ " for reason "+str(e), None) return None
def _get_path(ctx, save=False, default_name=None, filter_names=None, default_filter=None, default_dir=None): fp = ctx.getServiceManager().createInstanceWithContext( "com.sun.star.ui.dialogs.FilePicker", ctx) fp.initialize((10 if save else 0,)) if filter_names: for filter_name, pattern in filter_names: fp.appendFilter(filter_name, pattern) if default_filter: fp.setCurrentFilter(filter_names[default_filter]) if default_name: fp.setDefaultName(default_name) if default_dir: fp.setDisplayDirectory(default_dir) if fp.execute(): dest_url = fp.getFiles()[0] return unohelper.fileUrlToSystemPath(dest_url) else: return
def __extract_families(self) -> None: ged = unohelper.fileUrlToSystemPath(self.props['URL']) config = { 'input': ged, } importer = ged2dot.GedcomImport() graph = importer.load(config) self.family_dict = {} for node in graph: if not isinstance(node, ged2dot.Family): continue help_string = "" if node.husb and node.husb.get_surname(): help_string += node.husb.get_surname() help_string += "-" if node.wife and node.wife.get_surname(): help_string += node.wife.get_surname() key = f"{node.get_identifier()} ({help_string})" self.family_dict[key] = node
def filter(self, props: Dict[str, Any]) -> bool: try: self.props = self.toDict(props) path = unohelper.fileUrlToSystemPath(self.props["URL"]) buf = self.__toSvg(path) xInputStream = self.createUnoService("io.SequenceInputStream") xInputStream.initialize((uno.ByteSequence(buf),)) xFilter = self.createUnoService("comp.Draw.SVGFilter") xFilter.setTargetDocument(self.xDstDoc) value = PropertyValue() value.Name = "InputStream" value.Value = xInputStream xFilter.filter((value,)) return True except Exception: self.printTraceback() return False
def createDB(db_defaultname): global crout crout = 'createDB' global last_input_createDB ## last_input_createDB = str(db_defaultname) fileurl=getDBFilename(db_defaultname) if fileurl: DB = Context.createInstance() DB.URL = "sdbc:embedded:hsqldb" DB.DatabaseDocument.storeAsURL(fileurl, ()) filepath = unohelper.fileUrlToSystemPath(fileurl) filename = os.path.basename(filepath) datasource = Context.getByName(fileurl) dbname = filename[:-4] Context.registerObject(dbname, datasource) return dbname else: return None
def filter(self, props): try: self.props = self.toDict(props) path = unohelper.fileUrlToSystemPath(self.props["URL"]) buf = self.__toSvg(path) xInputStream = self.createUnoService("io.SequenceInputStream") xInputStream.initialize((uno.ByteSequence(buf), )) xFilter = self.createUnoService("comp.Draw.SVGFilter") xFilter.setTargetDocument(self.xDstDoc) value = PropertyValue() value.Name = "InputStream" value.Value = xInputStream xFilter.filter((value, )) return True except: self.printTraceback() return False
def createDB(db_defaultname): global crout crout = 'createDB' global last_input_createDB ## last_input_createDB = str(db_defaultname) fileurl = getDBFilename(db_defaultname) if fileurl: DB = Context.createInstance() DB.URL = "sdbc:embedded:hsqldb" DB.DatabaseDocument.storeAsURL(fileurl, ()) filepath = unohelper.fileUrlToSystemPath(fileurl) filename = os.path.basename(filepath) datasource = Context.getByName(fileurl) dbname = filename[:-4] Context.registerObject(dbname, datasource) return dbname else: return None
def __extract_families(self) -> None: ged = unohelper.fileUrlToSystemPath(self.props['URL']) config_dict = { 'ged2dot': { 'input': ged, } } config = ged2dot.Config(config_dict) model = ged2dot.Model(config) model.load(config.input) self.family_dict = {} for i in model.families: help_string = "" if i.husb and i.husb.surname: help_string += i.husb.surname help_string += "-" if i.wife and i.wife.surname: help_string += i.wife.surname key = "%s (%s)" % (i.fid, help_string) self.family_dict[key] = i
def getConfigs(consts): ctx, smgr, configurationprovider, css, properties, nodepath, simplefileaccess = consts fns_keys = "SERVICE", "INTERFACE", "PROPERTY", "INTERFACE_METHOD", "INTERFACE_ATTRIBUTE", "NOLINK" # fnsのキーのタプル。 node = PropertyValue(Name="nodepath", Value="{}OptionDialog".format(nodepath)) root = configurationprovider.createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess", (node,)) offline, refurl, refdir, idlstext = root.getPropertyValues(properties) # コンポーネントデータノードから値を取得する。 prefix = "https://{}".format(refurl) if offline: # ローカルリファレンスを使うときはprefixを置換する。 pathsubstservice = smgr.createInstanceWithContext("com.sun.star.comp.framework.PathSubstitution", ctx) fileurl = pathsubstservice.substituteVariables(refdir, True) # $(inst)を変換する。fileurlが返ってくる。 if simplefileaccess.exists(fileurl): systempath = os.path.normpath(unohelper.fileUrlToSystemPath(fileurl)) # fileurlをシステムパスに変換して正規化する。 prefix = "file://{}".format(systempath) else: raise RuntimeError("Local API Reference does not exists.") if not prefix.endswith("/"): prefix = "{}/".format(prefix) idls = "".join(idlstext.split()).split(",") # xmlがフォーマットされていると空白やタブが入ってくるのでそれを除去してリストにする。 idlsset = set("{}{}".format(css, i) if i.startswith(".") else i for i in idls) # "com.sun.star"が略されていれば付ける。 return ctx, configurationprovider, css, fns_keys, offline, prefix, idlsset
def __extractFamilies(self): ged = unohelper.fileUrlToSystemPath(self.props['URL']) configDict = { 'ged2dot': { 'input': ged, } } config = ged2dot.Config(configDict) model = ged2dot.Model(config) model.load(config.input) self.familyDict = {} for i in model.families: help = "" if i.husb and i.husb.surname: help += i.husb.surname help += "-" if i.wife and i.wife.surname: help += i.wife.surname key = "%s (%s)" % (i.id, help) self.familyDict[key] = i
def filter(self, props: Dict[str, Any]) -> bool: try: self.props = self.to_dict(props) path = unohelper.fileUrlToSystemPath(self.props["URL"]) buf = self.__to_svg(path) input_stream = self.create_uno_service("io.SequenceInputStream") input_stream.initialize((uno.ByteSequence(buf), )) svg_filter = self.create_uno_service("comp.Draw.SVGFilter") svg_filter.setTargetDocument(self.dst_doc) value = PropertyValue() value.Name = "InputStream" value.Value = input_stream svg_filter.filter((value, )) return True # pylint: disable=broad-except except Exception: self.print_traceback() return False
def trigger(self, args): try: gdoc = self.desktop.getCurrentComponent() win = gdoc.CurrentController.Frame.ContainerWindow if not gdoc: show_error("Need an opened file to create a document", win) return if gdoc.URL in PLUGIN.documents: show_error("Current file already attached to a document", win) return dialog = CreateDialog(self.ctx) resp = dialog.run() if dialog.doc_created and gdoc.URL not in PLUGIN.documents: path = unohelper.fileUrlToSystemPath(gdoc.URL) close(gdoc, self.desktop) try: os.remove(path) except os.error: pass except: traceback.print_exc()
def macro(): ctx = XSCRIPTCONTEXT.getComponentContext() # コンポーネントコンテクストの取得。 smgr = ctx.getServiceManager() # サービスマネージャーの取得。 doc = XSCRIPTCONTEXT.getDocument() # マクロを起動した時のドキュメントのモデルを取得。 docframe = doc.getCurrentController().getFrame() # モデル→コントローラ→フレーム、でドキュメントのフレームを取得。 docwindow = docframe.getContainerWindow() # ドキュメントのウィンドウ(コンテナウィンドウ=ピア)を取得。 toolkit = docwindow.getToolkit() # ピアからツールキットを取得。 taskcreator = smgr.createInstanceWithContext('com.sun.star.frame.TaskCreator', ctx) args = NamedValue("PosSize", Rectangle(100, 100, 530, 290)), NamedValue("FrameName", "ImageControlSample") # , NamedValue("MakeVisible", True) # TaskCreatorで作成するフレームのコンテナウィンドウのプロパティ。 frame = taskcreator.createInstanceWithArguments(args) # コンテナウィンドウ付きの新しいフレームの取得。 window = frame.getContainerWindow() # 新しいコンテナウィンドウを新しいフレームから取得。 frame.setTitle("Image Control Sample") # フレームのタイトルを設定。 docframe.getFrames().append(frame) # 新しく作ったフレームを既存のフレームの階層に追加する。 actionlistener = ActionListener(ctx, smgr, frame) # ボタンにつけるリスナー。コントロールコンテナはコントロールが追加されてから取得する。 margin_horizontal = 20 # 水平マージン margin_vertical = 13 # 垂直マージン window_width = 537 # ウィンドウ幅 window_height = 287 # ウィンドウの高さ headerlabel_height = 36 # Headerlabelの高さ。 line_height = 23 # Editコントロールやボタンコントロールの高さ buttonfilepick_width = 56 # ButtonFilePickボタンの幅。 buttonclose_width = 114 # ButtonCloseボタンの幅。 consts = margin_horizontal, margin_vertical, headerlabel_height, line_height, buttonfilepick_width, buttonclose_width # リスナーに渡す用。 pathsubstservice = smgr.createInstanceWithContext("com.sun.star.comp.framework.PathSubstitution", ctx) uno_path = pathsubstservice.getSubstituteVariableValue("$(prog)") # fileurlでprogramフォルダへのパスが返ってくる。 fileurl = "{}/intro.png".format(uno_path) # 画像ファイルへのfileurl imageurl = os.path.normpath(unohelper.fileUrlToSystemPath(fileurl)) # fileurlをシステム固有のパスに変換して正規化する。 controlcontainer, addControl = controlcontainerCreator(ctx, smgr, {"PositionX": 0, "PositionY": 0, "Width": window_width, "Height": window_height, "BackgroundColor": 0xF0F0F0, "PosSize": POSSIZE}) # ウィンドウに表示させるコントロールコンテナを取得。BackgroundColor: -1は透過色のもよう。 fixedtext1 = addControl("FixedText", {"PositionX": margin_horizontal, "PositionY": margin_vertical, "Width": window_width-margin_horizontal*2, "Height": headerlabel_height, "Label": "This code-sample demonstrates how to create an ImageControlSample within a dialog.", "MultiLine": True, "PosSize": POSSIZE}) imagecontrol1 = addControl("ImageControl", {"PositionX": margin_horizontal, "PositionY": margin_vertical*2+headerlabel_height, "Width": window_width-margin_horizontal*2, "Height": window_height-margin_vertical*5-line_height*2-headerlabel_height, "Border": 0, "ScaleImage": True, "ScaleMode": ISOTROPIC, "ImageURL": fileurl, "PosSize": POSSIZE}) # "ScaleImage": Trueで画像が歪む。 edit1 = addControl("Edit", {"PositionX": margin_horizontal, "PositionY": window_height-margin_vertical*2-line_height*2, "Width": window_width-margin_horizontal*2-buttonfilepick_width-2, "Height": line_height, "Text": imageurl, "PosSize": POSSIZE}) button1 = addControl("Button", {"PositionX": window_width-margin_horizontal-buttonfilepick_width, "PositionY": window_height-margin_vertical*2-line_height*2, "Width": buttonfilepick_width, "Height": line_height, "Label": "~Browse", "PosSize": POSSIZE}, {"setActionCommand": "filepick" ,"addActionListener": actionlistener}) # PushButtonTypeの値はEnumではエラーになる。 button2 = addControl("Button", {"PositionX": (window_width-buttonclose_width)/2, "PositionY": window_height-margin_vertical-line_height, "Width": buttonclose_width, "Height": line_height, "Label": "~Close dialog", "PosSize": POSSIZE}, {"setActionCommand": "close" ,"addActionListener": actionlistener}) # PushButtonTypeは動かない。 actionlistener.setControl(imagecontrol1, edit1) # getControl()で追加するコントロールが追加されてからコントロールコンテナを取得する。 controlcontainer.createPeer(toolkit, window) # ウィンドウにコントロールを描画。 controlcontainer.setVisible(True) # コントロールの表示。 window.setVisible(True) # ウィンドウの表示。 controls = controlcontainer, fixedtext1, imagecontrol1, edit1, button1, button2 window.addWindowListener(WindowListener(controls, consts)) # setVisible(True)でも呼び出されるので、その後で実行する。
def exec_SetGnuCashFilePaths(): """ Definition of data source and target files, creation of empty database """ global fp_read, fp_write global crout crout = 'SetGnuCashFilePaths' # uno service for filepickers # There was a bug under ubuntu 8.04 when I took the normal, # i.e. Gnom FilePicker, so I had to take the Office File Picker fp_read = smgr.createInstanceWithContext( "com.sun.star.ui.dialogs.OfficeFilePicker", ctx) fp_write = smgr.createInstanceWithContext( "com.sun.star.ui.dialogs.OfficeFilePicker", ctx) GCFileURL = getGCFilename() if GCFileURL: GCFile = unohelper.fileUrlToSystemPath(GCFileURL) else: return None settings = open(settings_filepath(), 'w') entrance_line = settings_textentrance + set_macro + '\n' settings.write(entrance_line) settings.write(settings_textinp) settings.write(GCFile.encode(lcodec) + '\n') gcfilename = os.path.basename(GCFile) dbname = createDB(gcfilename) if dbname: settings.write(settings_textoutp) settings.write(dbname.encode(lcodec) + '\n') else: return None settings.close() MessageBox('A new Openoffice.org database has been created.\n' + 'To fill with data please run macro "fillGnuCashDB."', MsgType="infobox")
def exec_SetGnuCashFilePaths(): """ Definition of data source and target files, creation of empty database """ global fp_read, fp_write global crout crout = 'SetGnuCashFilePaths' # uno service for filepickers # There was a bug under ubuntu 8.04 when I took the normal, # i.e. Gnom FilePicker, so I had to take the Office File Picker fp_read = smgr.createInstanceWithContext( "com.sun.star.ui.dialogs.OfficeFilePicker", ctx) fp_write = smgr.createInstanceWithContext( "com.sun.star.ui.dialogs.OfficeFilePicker", ctx) GCFileURL = getGCFilename() if GCFileURL: GCFile = unohelper.fileUrlToSystemPath(GCFileURL) else: return None settings = open(settings_filepath(), 'w') entrance_line = settings_textentrance + set_makro + '\n' settings.write(entrance_line) settings.write(settings_textinp) settings.write(GCFile.encode(lcodec) + '\n') gcfilename = os.path.basename(GCFile) dbname = createDB(gcfilename) if dbname: settings.write(settings_textoutp) settings.write(dbname.encode(lcodec) + '\n') else: return None settings.close() MessageBox('A new Openoffice.org database has been created.\n' + 'To fill with data please run makro "fillGnuCashDB."', MsgType="infobox")
def getModuleFromUrl(self, url): if DEBUG: print("pythonloader: interpreting url " + url) protocol, dependent = splitUrl(url) if "vnd.sun.star.expand" == protocol: exp = self.ctx.getValueByName( "/singletons/com.sun.star.util.theMacroExpander") url = exp.expandMacros(dependent) protocol, dependent = splitUrl(url) if DEBUG: print("pythonloader: after expansion " + protocol + ":" + dependent) try: if "file" == protocol: # remove \..\ sequence, which may be useful e.g. in the build env url = unohelper.absolutize(url, url) # did we load the module already ? mod = g_loadedComponents.get(url) if not mod: mod = types.ModuleType("uno_component") # check for pythonpath.zip beside .py files checkForPythonPathBesideComponent(url[0:url.rfind('/')]) # read the file filename = unohelper.fileUrlToSystemPath(url) with open(filename, encoding='utf_8') as fileHandle: src = fileHandle.read().replace("\r", "") if not src.endswith("\n"): src = src + "\n" # compile and execute the module codeobject = compile(src, encfile(filename), "exec") mod.__file__ = filename exec(codeobject, mod.__dict__) g_loadedComponents[url] = mod return mod elif "vnd.openoffice.pymodule" == protocol: nSlash = dependent.rfind('/') if -1 != nSlash: path = unohelper.fileUrlToSystemPath(dependent[0:nSlash]) dependent = dependent[nSlash + 1:len(dependent)] if not path in sys.path: sys.path.append(path) mod = __import__(dependent) path_component, dot, rest = dependent.partition('.') while dot == '.': path_component, dot, rest = rest.partition('.') mod = getattr(mod, path_component) return mod else: if DEBUG: print("Unknown protocol '" + protocol + "'") raise RuntimeException( "PythonLoader: Unknown protocol " + protocol + " in url " + url, self) except Exception as e: if DEBUG: print("Python import exception " + str(type(e)) + " message " + str(e) + " args " + str(e.args)) raise RuntimeException( "Couldn't load " + url + " for reason " + str(e), None) return None
from com.sun.star.beans import PropertyValue # Insert our own directory into sys.path. Normally that's already done, and # even if it's not, __file__ is defined, so it's trivial to do so. But # that's not the case here. Seems the only way to do this is to read a # configuration value, where %origin% gets replaced with the directory # we're interested in. ctx = uno.getComponentContext() configurationProvider = ctx.ServiceManager.createInstance('com.sun.star.configuration.ConfigurationProvider') value = PropertyValue() value.Name = 'nodepath' value.Value = 'hu.vmiklos.libreoffice.Draw.GedcomImportFilter.Settings/Tokens' configurationAccess = configurationProvider.createInstanceWithArguments('com.sun.star.configuration.ConfigurationAccess', (value,)) origin = configurationAccess.Origin # Actually the returned value still contains 'vnd.sun.star.expand:$UNO_USER_PACKAGES_CACHE', let's expand that. expander = ctx.getValueByName('/singletons/com.sun.star.util.theMacroExpander') url = expander.expandMacros(origin).replace('vnd.sun.star.expand:', '') path = unohelper.fileUrlToSystemPath(url) sys.path.insert(0, path) import dialog import filter g_ImplementationHelper = unohelper.ImplementationHelper() g_ImplementationHelper.addImplementation(dialog.GedcomDialog, "hu.vmiklos.libreoffice.comp.Draw.GedcomImportDialog", ("com.sun.star.ui.dialogs.FilterOptionsDialog",)) g_ImplementationHelper.addImplementation(filter.GedcomImport, "hu.vmiklos.libreoffice.comp.Draw.GedcomImportFilter", ("com.sun.star.document.ImportFilter",)) except: traceback.print_exc(file=sys.stderr) # vim:set shiftwidth=4 softtabstop=4 expandtab:
def settings_filepath(): userdir_url = PathSettings.UserConfig userdir = unohelper.fileUrlToSystemPath(userdir_url) userfile = os.path.join(userdir, 'GnuCashFilePaths.txt') return userfile
import sys from unohelper import fileUrlToSystemPath # This will modify path to include movelister module be part of it. This is # needed because this file is the main entry to the program and it can be # executed from three different contexts: from command-line, from LibreOffice # when macros are part of the system files and from LibreOffice when movelister # source files are packed inside LibreOffice document for release. if __name__ == '__main__': sys.path.append(os.path.join(os.path.dirname('__file__'), 'pythonpath')) elif __name__ == 'ooo_script_framework': # Name when executed from LibreOffice. # When executed from LibreOffice, add Python files inside to the document # be part of the system path so they can be imported normally. doc = XSCRIPTCONTEXT.getDocument() url = fileUrlToSystemPath('{}/{}'.format(doc.URL, 'Scripts/python/pythonpath')) sys.path.insert(0, url) from movelister.core import cursor, names, errors # noqa from movelister.core.namedRanges import NamedRanges from movelister.core.context import Context # noqa from movelister.format import action, overview # noqa from movelister.format.details import DetailsFormatter # noqa from movelister.format.overview import OverviewFormatter # noqa from movelister.process.updateOverview import UpdateOverview # noqa from movelister.process.updateDetails import UpdateDetails # noqa from movelister.process import conditionalFormat # noqa from movelister.process.updateStyles import UpdateStyles # noqa from movelister.sheet import helper # noqa from movelister.sheet.about import About # noqa from movelister.sheet.details import Details # noqa
def get_package_file(self, package, filename): pip = self.ctx.getByName("/singletons/com.sun.star.deployment.PackageInformationProvider") url = pip.getPackageLocation(package) + "/" + filename return unohelper.fileUrlToSystemPath(url)
def getModuleFromUrl( self, url ): if DEBUG: print("pythonloader: interpreting url " + url) protocol, dependent = splitUrl( url ) if "vnd.sun.star.expand" == protocol: exp = self.ctx.getValueByName( "/singletons/com.sun.star.util.theMacroExpander" ) url = exp.expandMacros(dependent) protocol,dependent = splitUrl( url ) if DEBUG: print("pythonloader: after expansion " + protocol + ":" + dependent) try: if "file" == protocol: # remove \..\ sequence, which may be useful e.g. in the build env url = unohelper.absolutize( url, url ) # did we load the module already ? mod = g_loadedComponents.get( url ) if not mod: mod = imp.new_module("uno_component") # check for pythonpath.zip beside .py files checkForPythonPathBesideComponent( url[0:url.rfind('/')] ) # read the file filename = unohelper.fileUrlToSystemPath( url ) if sys.version >= '3': fileHandle = open( filename, encoding='utf_8' ) else: fileHandle = open( filename ) src = fileHandle.read().replace("\r","") if not src.endswith( "\n" ): src = src + "\n" # compile and execute the module codeobject = compile( src, encfile(filename), "exec" ) exec(codeobject, mod.__dict__) mod.__file__ = encfile(filename) g_loadedComponents[url] = mod return mod elif "vnd.openoffice.pymodule" == protocol: nSlash = dependent.rfind('/') if -1 != nSlash: path = unohelper.fileUrlToSystemPath( dependent[0:nSlash] ) dependent = dependent[nSlash+1:len(dependent)] if not path in sys.path: sys.path.append( path ) mod = __import__( dependent ) path_component, dot, rest = dependent.partition('.') while dot == '.': path_component, dot, rest = rest.partition('.') mod = getattr(mod, path_component) return mod else: if DEBUG: print("Unknown protocol '" + protocol + "'"); raise RuntimeException( "PythonLoader: Unknown protocol " + protocol + " in url " +url, self ) except Exception as e: if DEBUG: print ("Python import exception " + str(type(e)) + " message " + str(e) + " args " + str(e.args)); raise RuntimeException( "Couldn't load " + url + " for reason " + str(e), None ) return None
def initpath(self): informationprovider = self.ctx.getValueByName( '/singletons/com.sun.star.deployment.PackageInformationProvider') self.path = unohelper.fileUrlToSystemPath( informationprovider.getPackageLocation('org.libreoffice.barcode'))
def _substitute_path(self, path): return unohelper.fileUrlToSystemPath( self._create("com.sun.star.util.PathSubstitution").\ substituteVariables("$(prog)/services.rdb", True))
def mousePressed(self, mouseevent): ctx, smgr, doc = self.args txt = mouseevent.Source.getText() fileurl = txt.split('"')[1] # エラー箇所のfileurlを取得。 lineno = txt.split(',')[1].split(" ")[2] # エラー箇所の行番号を取得。 # Geayでエラー箇所を開く。 if all([fileurl, lineno]): # ファイル名と行番号が取得出来ている時。 flg = (platform.system() == "Windows") # Windowsかのフラグ。 if flg: # Windowsの時 geanypath = "C:\\Program Files (x86)\\Geany\\bin\\geany.exe" # 64bitでのパス。パス区切りは\\にしないとエスケープ文字に反応してしまう。 if not os.path.exists( geanypath ): # binフォルダはなぜかos.path.exists()は常にFalseになるので使えない。 geanypath = "C:\\Program Files\\Geany\\bin\\geany.exe" # 32bitでのパス。 if not os.path.exists(geanypath): geanypath = "" else: # Linuxの時。 p = subprocess.run( ["which", "geany"], universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) # which geanyの結果をuniversal_newlines=Trueで文字列で取得。 geanypath = p.stdout.strip() # /usr/bin/geany が返る。 componentwindow = doc.getCurrentController().ComponentWindow toolkit = componentwindow.getToolkit() if geanypath: # geanyがインストールされている時。 msg = "Geanyでソースのエラー箇所を一時ファイルで表示しますか?" msgbox = toolkit.createMessageBox( componentwindow, QUERYBOX, MessageBoxButtons.BUTTONS_YES_NO + MessageBoxButtons.DEFAULT_BUTTON_YES, "myRs", msg) if msgbox.execute() == MessageBoxResults.YES: simplefileaccess = smgr.createInstanceWithContext( "com.sun.star.ucb.SimpleFileAccess", ctx) tempfile = smgr.createInstanceWithContext( "com.sun.star.io.TempFile", ctx) # 一時ファイルを取得。一時フォルダを利用するため。 urltransformer = smgr.createInstanceWithContext( "com.sun.star.util.URLTransformer", ctx) dummy, tempfileURL = urltransformer.parseStrict( URL(Complete=tempfile.Uri)) dummy, fileURL = urltransformer.parseStrict( URL(Complete=fileurl)) destfileurl = "".join( [tempfileURL.Protocol, tempfileURL.Path, fileURL.Name]) simplefileaccess.copy(fileurl, destfileurl) # マクロファイルを一時フォルダにコピー。 filepath = unohelper.fileUrlToSystemPath( destfileurl) # 一時フォルダのシステムパスを取得。 if flg: # Windowsの時。Windowsではなぜか一時ファイルが残る。削除してもLibreOffice6.0.5を終了すると復活して残る。C:\Users\pq\AppData\Local\Temp\ os.system('start "" "{}" "{}:{}"'.format( geanypath, filepath, lineno )) # バックグランドでGeanyでカーソルの行番号を指定して開く。第一引数の""はウィンドウタイトル。 else: os.system("{} {}:{} &".format( geanypath, filepath, lineno)) # バックグランドでGeanyでカーソルの行番号を指定して開く。 else: msg = "Geanyがインストールされていません。" msgbox = toolkit.createMessageBox(componentwindow, ERRORBOX, MessageBoxButtons.BUTTONS_OK, "myRs", msg) msgbox.execute()
# Insert our own directory into sys.path. Normally that's already done, and # even if it's not, __file__ is defined, so it's trivial to do so. But # that's not the case here. Seems the only way to do this is to read a # configuration value, where %origin% gets replaced with the directory # we're interested in. CTX = uno.getComponentContext() CONFIGURATION_PROVIDER = CTX.ServiceManager.createInstance('com.sun.star.configuration.ConfigurationProvider') VALUE = PropertyValue() VALUE.Name = 'nodepath' VALUE.Value = 'hu.vmiklos.libreoffice.Draw.GedcomImportFilter.Settings/Tokens' CONFIGURATION_ACCESS = CONFIGURATION_PROVIDER.createInstanceWithArguments('com.sun.star.configuration.ConfigurationAccess', (VALUE,)) ORIGIN = CONFIGURATION_ACCESS.Origin # Actually the returned value still contains 'vnd.sun.star.expand:$UNO_USER_PACKAGES_CACHE', let's expand that. EXPANDER = CTX.getValueByName('/singletons/com.sun.star.util.theMacroExpander') URL = EXPANDER.expandMacros(ORIGIN).replace('vnd.sun.star.expand:', '') PATH = unohelper.fileUrlToSystemPath(URL) sys.path.insert(0, PATH) import dialog import importer # pythonloader.py has this name hardcoded # pylint: disable=invalid-name g_ImplementationHelper = unohelper.ImplementationHelper() g_ImplementationHelper.addImplementation(dialog.GedcomDialog, "hu.vmiklos.libreoffice.comp.Draw.GedcomImportDialog", ("com.sun.star.ui.dialogs.FilterOptionsDialog",)) g_ImplementationHelper.addImplementation(importer.GedcomImport, "hu.vmiklos.libreoffice.comp.Draw.GedcomImportFilter", ("com.sun.star.document.ImportFilter",)) # pylint: disable=broad-except except Exception: traceback.print_exc(file=sys.stderr) # vim:set shiftwidth=4 softtabstop=4 expandtab: