]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpaperview.py
Add python lyxpaperview script
[lyx.git] / lib / scripts / lyxpaperview.py
1 #! /usr/bin/python3
2 # -*- coding: utf-8 -*-
3
4 # file lyxpaperview.py
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
7
8 # author Jürgen Spitzmüller
9 # Full author contact details are available in file CREDITS
10
11 # This script searches the home directory for a PDF or PS
12 # file with a name containing year and author. If found,
13 # it opens the file in a viewer. 
14
15 import getopt, os, sys, subprocess
16
17 pdf_viewers = ('pdfview', 'kpdf', 'okular', 'qpdfview --unique',
18                'evince', 'xreader', 'kghostview', 'xpdf', 'SumatraPDF',
19                'acrobat', 'acroread', 'mupdf',
20                'gv', 'ghostview', 'AcroRd32', 'gsview64', 'gsview32')
21
22 ps_viewers = ("kghostview", "okular", "qpdfview --unique",
23               "evince", "xreader", "gv", "ghostview -swap",
24               "gsview64", "gsview32")
25
26 def message(message):
27     sys.stderr.write("lyxpaperview: %s\n" % message)
28
29 def error(message):
30     sys.stderr.write("lyxpaperview error: %s\n" % message)
31     exit(1)
32
33 def usage(prog_name):
34     msg = "Usage: %s [-v pdfviewer] [-w psviewer] year author"
35     return  msg % prog_name
36
37 # Copied from lyxpreview_tools.py
38 # PATH and PATHEXT environment variables
39 path = os.environ["PATH"].split(os.pathsep)
40 extlist = ['']
41 if "PATHEXT" in os.environ:
42     extlist += os.environ["PATHEXT"].split(os.pathsep)
43 extlist.append('.py')
44
45 def find_exe(candidates):
46     global extlist, path
47
48     for command in candidates:
49         prog = command.split()[0]
50         for directory in path:
51             for ext in extlist:
52                 full_path = os.path.join(directory, prog + ext)
53                 if os.access(full_path, os.X_OK):
54                     # The thing is in the PATH already (or we wouldn't
55                     # have found it). Return just the basename to avoid
56                     # problems when the path to the executable contains
57                     # spaces.
58                     if full_path.lower().endswith('.py'):
59                         return command.replace(prog, '"%s" "%s"'
60                             % (sys.executable, full_path))
61                     return command
62
63     return None
64
65
66 def find_exe_or_terminate(candidates):
67     exe = find_exe(candidates)
68     if exe == None:
69         error("Unable to find executable from '%s'" % " ".join(candidates))
70
71     return exe
72
73 def find(year, author, path):
74     if os.name != 'nt':
75         # use locate if possible (faster)
76         if find_exe(['locate']):
77             p1 = subprocess.Popen(['locate', '-i', author], stdout=subprocess.PIPE)
78             p2 = subprocess.Popen(['grep', '-Ei', '\.pdf$|\.ps$'], stdin=p1.stdout, stdout=subprocess.PIPE)
79             p3 = subprocess.Popen(['grep', year], stdin=p2.stdout, stdout=subprocess.PIPE)
80             p4 = subprocess.Popen(['head', '-n 2'], stdin=p3.stdout, stdout=subprocess.PIPE)
81             p1.stdout.close()
82             output = p4.communicate()
83             return output[0].decode("utf8")[:-1]# strip trailing '\n'
84      # FIXME add something for windows as well?
85      # Maybe dir /s /b %WINDIR%\*author* | findstr .*year.*\."ps pdf"
86
87     for root, dirs, files in os.walk(path):
88         for fname in files:
89             lfname = fname.lower()
90             if lfname.endswith(('.pdf', '.ps')) and lfname.find(author) != -1 and lfname.find(year) != -1:
91                 return os.path.join(root, fname)
92     return ""
93
94 def main(argv):
95     progname = argv[0]
96     
97     opts, args = getopt.getopt(sys.argv[1:], "v:w:")
98     pdfviewer = ""
99     psviewer = ""
100     for o, v in opts:
101       if o == "-v":
102         pdfviewer = v
103       if o == "-w":
104         psviewer = v
105     
106     if len(args) != 2:
107       error(usage(progname))
108
109     year = args[0]
110     author = args[1]
111
112     result = find(year, author.lower(), path = os.environ["HOME"])
113     if result == "":
114         message("no document found!")
115         return 0
116     else:
117         message("found document %s" % result)
118
119     viewer = ""
120     if result.lower().endswith('.ps'):
121         if psviewer == "":
122             viewer = find_exe_or_terminate(ps_viewers)
123         else:
124             viewer = psviewer
125     else:
126         if pdfviewer == "":
127            viewer = find_exe_or_terminate(pdf_viewers)
128         else:
129             viewer = pdfviewer
130     
131     subprocess.call([viewer, result])
132     
133     return 0
134
135 if __name__ == "__main__":
136     main(sys.argv)