File: run

package info (click to toggle)
frescobaldi 1.1.4-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 4,240 kB
  • ctags: 2,434
  • sloc: python: 15,614; lisp: 28; sh: 25; makefile: 2
file content (408 lines) | stat: -rwxr-xr-x 14,823 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
#!/usr/bin/env python

"""
Try to run Frescobaldi immediately without installing.
Does not require CMake and make for release tar balls.
Checks the python version and modules.
If not Python 2.6 try to rerun ourselves with python 2.6.
Creates a local installdir (inside the frescobaldi-x.x.x directory).
Creates a menu in the local xdgdata-apps dir.
Records the current Okular textedit binding.
Adjusts some settings and directly runs Frescobaldi.
After having run this, users can run './frescobaldi' directly.
Calling python run or ./run again will display a dialog with options
to remove the Applications menu entry and restore the Okular binding.
"""

import glob, itertools, os, re, subprocess, sys

def findAllExe(command):
    """Returns an iterable over all occurences of the command in the PATH."""
    for p in os.environ.get("PATH", os.defpath).split(os.pathsep):
        path = os.path.join(p, command)
        if os.access(path, os.X_OK):
            yield path

def findExe(command):
    """Returns the first found command in the PATH or None if not found."""
    for path in findAllExe(command):
        return path

def die(msg):
    """Show a message and exit with exitcode 1."""
    try:
        KMessageBox.error(None, msg)
    except Exception:
        if os.environ.get('DISPLAY') and findExe('kdialog'):
            subprocess.call(['kdialog', '--error', msg])
        else:
            sys.stderr.write(msg+'\n')
    sys.exit(1)

def configure_file(infile, outfile, dictionary):
    """Replace variables in infile and write the result to outfile.
    
    Variables consist of uppercase letters and may contain underscores.
    They start and end with the ampersand character. E.g. @MODULE_DIR@.
    This is analogous to the CMake configure_file function.
    
    Raises KeyError if a variable does not exist in the dictionary.
    
    """
    with open(outfile, 'w') as f:
        f.write(re.sub(r'@([A-Z]+(_[A-Z]+)*)@',
            lambda m: dictionary[m.group(1)], open(infile).read()))

def makedirs(path, mode=0o777):
    """Like os.makedirs(), but doesn't error out if the full path exists."""
    if not os.path.exists(path):
        os.makedirs(path)

# html
p = lambda s: '<p>%s</p>\n' % s
li = lambda s: '<li>%s</li>\n' % s
ul = lambda *args: '<ul>\n%s</ul>\n' % ''.join(args)

# Python must be 2.6
if sys.version_info[:2] != (2, 6):
    # find Python 2.6
    for path in itertools.chain(
            findAllExe('python2.6'),
            findAllExe('python'),
            findAllExe('python26')):
        ver = subprocess.Popen(
            [path, "--version"], stderr=subprocess.PIPE).communicate()[1]
        if ' 2.6' in ver:
            os.execl(path, path, sys.argv[0])
    die("Could not find Python 2.6.\n\n"
        "Please install the 2.6 version of Python.")

# find out our directory
curdir = os.path.dirname(os.path.abspath(sys.argv[0]))
os.chdir(curdir)
sys.path.insert(0, curdir)

try:
    import sip
    sip.setapi("QString", 2)
    sip.setapi("QVariant", 2)
except Exception:
    die("Please install the Python-SIP module.\nCan't set the sip API.")

# check modules
import checkmodules
missing = checkmodules.checkModules()
if missing:
    die("The following Python modules are missing: %s.\n\n"
        "Please install them and try again." % ", ".join(missing))

# check versions
versions = checkmodules.checkVersions()
if versions:
    die("Some packages have outdated versions:\n\n" + "\n".join(versions))

# Everything look OK!

# brutally use some modules from Frescobaldi
sys.path[0] = os.path.join(curdir, 'python')

# Construct KApplication

import shutil

from PyKDE4.kdecore import KAboutData, KCmdLineArgs, KConfig, KGlobal, ki18n
from PyKDE4.kdeui import (
    KApplication, KDialog, KGuiItem, KMessageBox, KStandardGuiItem)
from PyKDE4.kio import KUrlRequesterDialog

aboutData = KAboutData(
    'frescobaldi_runner',       # appName
    'frescobaldi_runner',       # catalogName
    ki18n('Frescobaldi Runner'),# programName
    '1.0'                       # version
    )

KCmdLineArgs.init(sys.argv, aboutData)
app = KApplication()

# set some directories/values
data = {}

m = re.search(r'set\(VERSION\s+"(.*?)"', open('CMakeLists.txt').read())
if not m:
    die("Internal error: could not determine version from CMakeLists.txt")

data['VERSION'] = m.group(1)
data['MODULE_DIR'] = os.path.join(curdir, "python")
data['PYTHON_EXECUTABLE'] = sys.executable
data['CMAKE_INSTALL_PREFIX'] = os.path.join(curdir, 'image')
data['APP_DIR'] = os.path.join(
    data['CMAKE_INSTALL_PREFIX'], 'share', 'apps', 'frescobaldi')


icon_install_dir = KGlobal.dirs().saveLocation('icon', 'hicolor/scalable/apps/')
html_install_dir = KGlobal.dirs().saveLocation('html', 'en/')
xdgdata_apps_install_dir = KGlobal.dirs().saveLocation('xdgdata-apps')
locale_install_dir = os.path.join(
    data['CMAKE_INSTALL_PREFIX'], 'share', 'locale')

# some shortcuts
app_dir = data['APP_DIR']
desktop_file = os.path.join(xdgdata_apps_install_dir, 'frescobaldi.desktop')


class TarBall:
    """Used when running from a Frescobaldi release tar ball.
    
    Does not need CMake and make.
    
    """
    
    builddir = 'prebuilt'
    
    def makeImage(self):
        # puts some files under image/share/ ...
        makedirs(app_dir)
        
        for name in ('frescobaldiui.rc', 'expansions', 'lilydoc.css'):
            dest = os.path.join(app_dir, name)
            if os.path.exists(dest):
                os.remove(dest)
            os.symlink(os.path.join(curdir, 'data', name), dest)
        
        for name in ('rumor', 'icons'):
            dest = os.path.join(app_dir, name)
            if os.path.exists(dest):
                os.remove(dest)
            os.symlink(os.path.join(curdir, name), dest)
        
        # pics
        dest = os.path.join(app_dir, 'pics')
        if os.path.exists(dest):
            os.remove(dest)
        os.symlink(os.path.join(curdir, self.builddir, 'pics'), dest)
        
        # install mo files
        for mo in glob.glob(os.path.join(self.builddir, 'po', '*.mo')):
            lang = os.path.splitext(os.path.basename(mo))[0]
            langdir = os.path.join(locale_install_dir, lang, 'LC_MESSAGES')
            makedirs(langdir)
            shutil.copy(mo, os.path.join(langdir, 'frescobaldi.mo'))
        
    def installBinary(self):
        # create the frescobaldi 'binary'
        configure_file('frescobaldi.py', 'frescobaldi', data)
        os.chmod('frescobaldi', 0o744)
    
    def installFrescobaldi(self):
        # create the frescobaldi 'binary'
        self.installBinary()
        
        # put appIcon in icondir
        shutil.copy(
            os.path.join('data', 'frescobaldi-lily.svgz'),
            os.path.join(icon_install_dir, 'frescobaldi.svgz'))
        
        # install desktop file
        desktop = open(os.path.join('data', 'frescobaldi.desktop')).read()
        newdesktop = re.sub(r'\bExec=frescobaldi\b',
            'Exec=%s/frescobaldi' % curdir, desktop)
        with open(desktop_file, 'w') as f:
            f.write(newdesktop)

        # install link to documentation
        os.symlink(os.path.join(curdir, 'doc'),
            os.path.join(html_install_dir, 'frescobaldi'))
        

class SVN(TarBall):
    """Used when running from a Frescobaldi SVN checkout.
    
    Needs CMake and make, lilypond and msgfmt.
    
    """
    
    builddir = 'build'
    
    def makeImage(self):
        # run CMake
        # check some programs.
        missing = []
        if not findExe('cmake'):
            missing.append(
                "CMake is needed to run Frescobaldi from a SVN checkout.\n"
                "Please install CMake.")
        if not findExe('make'):
            missing.append(
                "Make is needed to run Frescobaldi from a SVN checkout.\n"
                "Please install a 'make' program.")
        if not findExe('convert'):
            missing.append(
                "'convert' (from ImageMagick) is needed to run Frescobaldi "
                "from a SVN checkout.\nPlease install ImageMagick.")
        if not findExe('msgfmt'):
            missing.append(
                "'msgfmt' (from Gettext) is needed to run Frescobaldi "
                "from a SVN checkout.\nPlease install Gettext.")
        if missing:
            die('\n\n'.join(missing))
        
        import ly.version
        for lily in findAllExe('lilypond'):
            if ly.version.LilyPondInstance(lily).version() >= (2, 13, 19):
                break
        else:
            config = KGlobal.config().group(None)
            lily = config.readEntry("lilypond", "lilypond")
            dlg = KUrlRequesterDialog(lily, 
                "LilyPond >= 2.13.19 is needed to run Frescobaldi from a SVN "
                "checkout.\n\nPlease install a recent LilyPond (e.g. from a "
                "binary download) and select the binary here.", None)
            if dlg.exec_():
                lily = dlg.selectedUrl().path()
                config.writeEntry("lilypond", lily)
                config.sync()
            else:
                sys.exit(1)
                
        makedirs(self.builddir)
        if subprocess.call([
            'cmake', '..',
            '-DCMAKE_INSTALL_PREFIX=' + data['CMAKE_INSTALL_PREFIX'],
            '-DPYTHON_EXECUTABLE=' + sys.executable,
            '-DLILYPOND_EXECUTABLE=' + lily,
            '-DBYTECOMPILE=NO',
            ], cwd=self.builddir):
            die("CMake exited with an error.")
        if subprocess.call(['make'], cwd=self.builddir):
            die("Make exited with an error.")
        if subprocess.call(['make', 'install'], cwd=self.builddir):
            die("'make install' exited with an error.")
            
    def installBinary(self):
        shutil.copy2(os.path.join(self.builddir, 'frescobaldi'), 'frescobaldi')
        os.chmod('frescobaldi', 0o744)


def removeFrescobaldi():
    # remove the frescobaldi 'binary'
    os.remove('frescobaldi')
    
    # remove appIcon
    os.remove(os.path.join(icon_install_dir, 'frescobaldi.svgz'))
    
    # remove desktop file
    os.remove(desktop_file)
    
    # remove link to documentation
    os.remove(os.path.join(html_install_dir, 'frescobaldi'))

def runFrescobaldi():
    subprocess.Popen([os.path.join(curdir, 'frescobaldi')],
        cwd=os.environ.get('HOME'))

def saveOkularPart():
    """Save the current OkularPart editor settings."""
    okularpartrc = KConfig("okularpartrc", KConfig.NoGlobals)
    group = okularpartrc.group("General")
    
    ourconfig = KGlobal.config()
    ourgroup = ourconfig.group('okular editor')
    
    ourgroup.writeEntry("ExternalEditor",
        group.readEntry("ExternalEditor", ""))
    ourgroup.writeEntry("ExternalEditorCommand",
        group.readEntry("ExternalEditorCommand", ""))
    ourconfig.sync()

def configureOkularPart():
    """Lets Frescobaldi configure itself as custom editor in Okular."""
    config = KConfig("frescobaldirc", KConfig.NoGlobals)
    group = config.group("")
    group.writeEntry("configure okularpart", True)
    group.sync()

def restoreOkularPart():
    """Restore the saved OkularPart editor settings."""
    okularpartrc = KConfig("okularpartrc", KConfig.NoGlobals)
    group = okularpartrc.group("General")
    
    ourconfig = KGlobal.config()
    ourgroup = ourconfig.group('okular editor')
    
    group.writeEntry("ExternalEditor",
        ourgroup.readEntry("ExternalEditor", ""))
    group.writeEntry("ExternalEditorCommand",
        ourgroup.readEntry("ExternalEditorCommand", ""))
    group.sync()

def main():
    # if the desktop file and the 'binary' do exist,
    # assume Frescobaldi is installed and can be run.
    if os.path.exists(desktop_file) and os.path.exists('frescobaldi'):
        # Frescobaldi can be run. Offer options to remove or run Frescobaldi
        result = KMessageBox.questionYesNoCancel(None,
                "Frescobaldi is available in your Applications menu.\n\n"
                "Here you can choose if you want to remove Frescobaldi from "
                "the menu or to run Frescobaldi.\n\n"
                "It is recommended that you remove Frescobaldi from the menu "
                "when you really install Frescobaldi, as that will install a "
                "system-wide Applications menu entry.",
            None,
            KGuiItem("Run Frescobaldi", 'system-run'),
            KGuiItem("Remove Frescobaldi from menu", 'edit-delete'),
            KStandardGuiItem.cancel())
        if result == KMessageBox.Yes:
            configureOkularPart()
            runFrescobaldi()
        elif result == KMessageBox.No:
            removeFrescobaldi()
            restoreOkularPart()
            configureOkularPart()
            
    else:
        # Frescobaldi seems not to be installed.
        if os.path.exists('prebuilt'):
            installer = TarBall()
        else:
            installer = SVN()
        installer.makeImage()
        installer.installFrescobaldi()
        saveOkularPart()
        configureOkularPart()
        msg = [
            p("Frescobaldi has been added to your Applications menu."),
            p("If you want to remove Frescobaldi from the menu, just run this "
              "'run' script again."),
            p("(It is recommended that you remove Frescobaldi from the menu "
              "when you really install Frescobaldi, as that will install a "
              "system-wide menu Applications menu entry.)"),
            p("Frescobaldi will now be started. Enjoy!")]
        notes = []
        if not findExe('lilypond'):
            notes.append(
                "LilyPond could not be found in your PATH. You really should "
                "install LilyPond to be able to do anything useful with "
                "Frescobaldi! Visit "
                "<a href=\"http://www.lilypond.org/\">www.lilypond.org</a> "
                "for more information.")
        if not findExe('okular'):
            notes.append(
                "The Okular PDF viewer could not be found in your PATH. "
                "The Okular KPart module provides the PDF preview, so "
                "if the preview doesn't work, you should install Okular.")
        if not findExe('rumor'):
            notes.append(
                "For music input via MIDI, the 'rumor' program is recommended. "
                "See the Frescobaldi User Guide (accessible from Frescobaldi "
                "with the F1 key) for more information.")
        if notes:
            msg.insert(1, p("Note:"))
            msg.insert(2, ul(*map(li, notes)))
        KMessageBox.information(None, '<qt>' + ''.join(msg), None, None,
            KMessageBox.Options(KMessageBox.Notify | KMessageBox.AllowLink))
        runFrescobaldi()
    return 0
    
if __name__ == "__main__":
    sys.exit(main())