summaryrefslogtreecommitdiffstats
path: root/scribus/plugins/scriptplugin/scripts
diff options
context:
space:
mode:
authorcraig <craig@11d20701-8431-0410-a711-e3c959e3b870>2012-01-01 11:40:09 +0000
committercraig <craig@11d20701-8431-0410-a711-e3c959e3b870>2012-01-01 11:40:09 +0000
commit7ed83b6c6666eb8b6b104c211ae7e52907350372 (patch)
tree4430b556abac0ad660a0aacf1887d77f85d8be02 /scribus/plugins/scriptplugin/scripts
downloadscribus-7ed83b6c6666eb8b6b104c211ae7e52907350372.tar.gz
scribus-7ed83b6c6666eb8b6b104c211ae7e52907350372.tar.xz
scribus-7ed83b6c6666eb8b6b104c211ae7e52907350372.zip
Branch 1.3.5 tree to 1.4.x tree, goodbye 1.3.x
git-svn-id: svn://scribus.net/branches/Version14x/Scribus@17163 11d20701-8431-0410-a711-e3c959e3b870
Diffstat (limited to 'scribus/plugins/scriptplugin/scripts')
-rw-r--r--scribus/plugins/scriptplugin/scripts/Autoquote.py167
-rw-r--r--scribus/plugins/scriptplugin/scripts/CMakeLists.txt20
-rw-r--r--scribus/plugins/scriptplugin/scripts/CalendarWizard.py670
-rw-r--r--scribus/plugins/scriptplugin/scripts/ChangeLog181
-rw-r--r--scribus/plugins/scriptplugin/scripts/ColorChart.py350
-rw-r--r--scribus/plugins/scriptplugin/scripts/DirectImageImport.py94
-rw-r--r--scribus/plugins/scriptplugin/scripts/FontSample.py1578
-rw-r--r--scribus/plugins/scriptplugin/scripts/InfoBox.py163
-rw-r--r--scribus/plugins/scriptplugin/scripts/NEWS40
-rw-r--r--scribus/plugins/scriptplugin/scripts/ReadMe1
-rw-r--r--scribus/plugins/scriptplugin/scripts/TODO13
-rw-r--r--scribus/plugins/scriptplugin/scripts/color2csv.py160
-rw-r--r--scribus/plugins/scriptplugin/scripts/csv2color.py187
-rw-r--r--scribus/plugins/scriptplugin/scripts/importcsv2table.py208
14 files changed, 3832 insertions, 0 deletions
diff --git a/scribus/plugins/scriptplugin/scripts/Autoquote.py b/scribus/plugins/scriptplugin/scripts/Autoquote.py
new file mode 100644
index 0000000..daa58f9
--- /dev/null
+++ b/scribus/plugins/scriptplugin/scripts/Autoquote.py
@@ -0,0 +1,167 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# File: quotes.py - changes typewriter quotes to typographic quotes
+# © 2010.08.28 Gregory Pittman
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+"""
+USAGE
+
+You must have a document open, and a text frame selected.
+There will be a valueDialog asking for your language for the quotes,
+the default is 'en', but change the default to suit your needs.
+Detected errors shut down the script with an appropriate message.
+
+"""
+import scribus
+
+if scribus.haveDoc():
+ c = 0
+ lang = scribus.valueDialog("Choose by language or country", 'Language: af, be, ch, cs, de, en, es, et, fi, fr,\n hu, is, lt, mk, nl, pl, ru, se, sk, sl, sq and uk\n are current choices','en')
+ if (lang == 'en'):
+ lead_double = u"\u201c"
+ follow_double = u"\u201d"
+ lead_single = u"\u2018"
+ follow_single = u"\u2019"
+ elif (lang == 'de'):
+ lead_double = u"\u201e"
+ follow_double = u"\u201c"
+ lead_single = u"\u2019"
+ follow_single = u"\u201a"
+ elif (lang == 'fr'):
+ lead_double = u"\u00ab"
+ follow_double = u"\u00bb"
+ lead_single = u"\u2018"
+ follow_single = u"\u2019" # am hoping this will cover contractions like je t'aime
+ elif (lang == 'pl'):
+ lead_double = u"\u201e"
+ follow_double = u"\u201d"
+ lead_single = u"\u201a"
+ follow_single = u"\u2019"
+ elif ((lang == 'se') or (lang == 'fi')):
+ lead_double = u"\u201d"
+ follow_double = u"\u201d"
+ lead_single = u"\u2019"
+ follow_single = u"\u2019"
+ elif (lang == 'af'):
+ lead_double = u"\u201c"
+ follow_double = u"\u201d"
+ lead_single = u"\u2018"
+ follow_single = u"\u2019"
+ elif (lang == 'sq'):
+ lead_double = u"\u201e"
+ follow_double = u"\u201c"
+ lead_single = u"\u2018"
+ follow_single = u"\u2019"
+ elif ((lang == 'be') or (lang == 'ch') or (lang == 'uk') or (lang == 'ru')):
+ lead_double = u"\u00ab"
+ follow_double = u"\u00bb"
+ lead_single = u"\u2039"
+ follow_single = u"\u203a"
+ elif (lang == 'uk'):
+ lead_double = u"\u00ab"
+ follow_double = u"\u00bb"
+ lead_single = u"\u2039"
+ follow_single = u"\u203a"
+ elif (lang == 'es'):
+ lead_double = u"\u00ab"
+ follow_double = u"\u00bb"
+ follow_double = u"\u201d"
+ lead_single = u"\u2018"
+ elif ((lang == 'lt') or (lang == 'mk') or (lang == 'is') or (lang == 'sk') or (lang == 'sl') or (lang == 'cs') or (lang == 'et')):
+ lead_double = u"\u201e"
+ follow_double = u"\u201c"
+ lead_single = u"\u2019"
+ follow_single = u"\u201a"
+ elif ((lang == 'hu') or (lang == 'nl')):
+ lead_double = u"\u201e"
+ follow_double = u"\u201d"
+ lead_single = u"\u00bb"
+ follow_single = u"\u00ab"
+ else:
+ scribus.messageBox('Language Error', 'You need to choose an available language', icon=0, button1=1)
+ sys.exit(2)
+
+else:
+ scribus.messageBox('Usage Error', 'You need a Document open', icon=0, button1=1)
+ sys.exit(2)
+
+if scribus.selectionCount() == 0:
+ scribus.messageBox('Scribus - Usage Error',
+ "There is no object selected.\nPlease select a text frame and try again.",
+ scribus.ICON_WARNING, scribus.BUTTON_OK)
+ sys.exit(2)
+if scribus.selectionCount() > 1:
+ scribus.messageBox('Scribus - Usage Error',
+ "You have more than one object selected.\nPlease select one text frame and try again.", scribus.ICON_WARNING, scribus.BUTTON_OK)
+ sys.exit(2)
+textbox = scribus.getSelectedObject()
+pageitems = scribus.getPageItems()
+boxcount = 1
+for item in pageitems:
+ if (item[0] == textbox):
+ if (item[1] != 4):
+ scribus.messageBox('Scribus - Usage Error', "This is not a textframe. Try again.", scribus.ICON_WARNING, scribus.BUTTON_OK)
+ sys.exit(2)
+contents = scribus.getTextLength(textbox)
+while c <= (contents -1):
+ if ((c + 1) > contents - 1):
+ nextchar = ' '
+ else:
+ scribus.selectText(c+1, 1, textbox)
+ nextchar = scribus.getText(textbox)
+ scribus.selectText(c, 1, textbox)
+ char = scribus.getText(textbox)
+ if (len(char) != 1):
+ c += 1
+ continue
+ if ((ord(char) == 34) and (c == 0)):
+ scribus.deleteText(textbox)
+ scribus.insertText(lead_double, c, textbox)
+ elif (ord(char) == 34):
+ if ((prevchar == '.') or (prevchar == ',') or (prevchar == '?') or (prevchar == '!')):
+ scribus.deleteText(textbox)
+ scribus.insertText(follow_double, c, textbox)
+ elif ((ord(prevchar) == 39) and ((nextchar != ' ') and (nextchar != ',') and (nextchar != '.'))):
+ scribus.deleteText(textbox)
+ scribus.insertText(lead_double, c, textbox)
+ elif ((nextchar == '.') or (nextchar == ',')):
+ scribus.deleteText(textbox)
+ scribus.insertText(follow_double, c, textbox)
+
+ elif ((prevchar == ' ') or ((nextchar != ' ') and (ord(nextchar) != 39))):
+ scribus.deleteText(textbox)
+ scribus.insertText(lead_double, c, textbox)
+ else:
+ scribus.deleteText(textbox)
+ scribus.insertText(follow_double, c, textbox)
+
+ if ((ord(char) == 39) and (c == 0)):
+ scribus.deleteText(textbox)
+ scribus.insertText(lead_single, c, textbox)
+ elif (ord(char) == 39):
+ if ((prevchar == '.') or (prevchar == ',') or (prevchar == '?') or (prevchar == '!')):
+ scribus.deleteText(textbox)
+ scribus.insertText(follow_single, c, textbox)
+ elif ((ord(prevchar) == 34) and ((nextchar != ' ') and (nextchar != ',') and (nextchar != '.'))):
+ scribus.deleteText(textbox)
+ scribus.insertText(lead_single, c, textbox)
+ elif ((prevchar != ' ') and (ord(prevchar) != 34) and (nextchar != ' ')):
+ scribus.deleteText(textbox)
+ scribus.insertText(follow_single, c, textbox)
+ elif ((prevchar == ' ') or ((nextchar != ' ') and (ord(nextchar) != 34))):
+ scribus.deleteText(textbox)
+ scribus.insertText(lead_single, c, textbox)
+ else:
+ scribus.deleteText(textbox)
+ scribus.insertText(follow_single, c, textbox)
+
+ c += 1
+ prevchar = char
+
+scribus.setRedraw(1)
+scribus.docChanged(1)
+endmessage = 'Successfully ran script\n Last character read was '+str(char) # Change this message to your liking
+scribus.messageBox("Finished", endmessage,icon=0,button1=1) \ No newline at end of file
diff --git a/scribus/plugins/scriptplugin/scripts/CMakeLists.txt b/scribus/plugins/scriptplugin/scripts/CMakeLists.txt
new file mode 100644
index 0000000..814d191
--- /dev/null
+++ b/scribus/plugins/scriptplugin/scripts/CMakeLists.txt
@@ -0,0 +1,20 @@
+INCLUDE_DIRECTORIES(
+"${CMAKE_SOURCE_DIR}/scribus"
+)
+
+INSTALL(FILES
+Autoquote.py
+CalendarWizard.py
+ColorChart.py
+DirectImageImport.py
+FontSample.py
+InfoBox.py
+ChangeLog
+NEWS
+ReadMe
+TODO
+color2csv.py
+csv2color.py
+importcsv2table.py
+ DESTINATION ${SCRIPTSDIR}
+)
diff --git a/scribus/plugins/scriptplugin/scripts/CalendarWizard.py b/scribus/plugins/scriptplugin/scripts/CalendarWizard.py
new file mode 100644
index 0000000..8b46eba
--- /dev/null
+++ b/scribus/plugins/scriptplugin/scripts/CalendarWizard.py
@@ -0,0 +1,670 @@
+# -*- coding: utf-8 -*-
+
+""" This is a simple 'Calendar creation wizard' for Scribus. It's a fully
+rewritten Calender.py from Scribus examples. Enjoy.
+
+DESCRIPTION & USAGE:
+This script needs Tkinter. It will create a GUI with available options
+for easy calendar page creation. You'll get new pages with calendar
+tables into a new document you are asked for. Position of the
+objects in page is calculated with the "golden-ratio" aspect from the
+page margins.
+
+Steps to create:
+ 1) Fill requested values in the Calendar dialog
+ 2) You will be prompted for new document
+ 3) You will be prompted for new paragraph style which will be used
+ in calendar text frames. It could be changed later.
+
+There are 2 types of calendar supported:
+ 1) Classic calendar with one month matrix per page. I suggest
+ here PORTRAIT orientation.
+ 2) Horizontal event calendar with one week per page with huge place
+ for human inputs. There should be LANDSCAPE imho.
+ 3) Horizontal event calendar with one week per page with huge place
+ for human inputs. There should be LANDSCAPE imho.
+
+But everything works with both orientations well of course too.
+
+AUTHORS:
+ Petr Vanek <petr@scribus.info>
+ Bernhard Reiter <ockham@raz.or.at>
+
+LICENSE:
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+"""
+
+import sys
+import calendar
+import datetime
+
+try:
+ from scribus import *
+except ImportError:
+ print "This Python script is written for the Scribus scripting interface."
+ print "It can only be run from within Scribus."
+ sys.exit(1)
+
+try:
+ # I wish PyQt installed everywhere :-/
+ from Tkinter import *
+ from tkFont import Font
+except ImportError:
+ print "This script requires Python's Tkinter properly installed."
+ messageBox('Script failed',
+ 'This script requires Python\'s Tkinter properly installed.',
+ ICON_CRITICAL)
+ sys.exit(1)
+
+
+localization = {
+'Catalan' :
+ [['Gener', 'Febrer', 'Març', 'Abril', 'Maig',
+ 'Juny', 'Juliol', 'Agost', 'Setembre',
+ 'Octubre', 'Novembre', 'Desembre'],
+ ['Dilluns', 'Dimarts', 'Dimecres', 'Dijous', 'Divendres', 'Dissabte', 'Diumenge']],
+'Catalan-short' :
+ [['Gener', 'Febrer', 'Març', 'Abril', 'Maig',
+ 'Juny', 'Juliol', 'Agost', 'Setembre',
+ 'Octubre', 'Novembre', 'Desembre'],
+ ['Dl', 'Dm', 'Dc', 'Dj', 'Dv', 'Ds', 'Dg']],
+# Catalan by "Cesc Morata" <atarom@gmail.com>
+'Czech' :
+ [['Leden', 'Únor', 'Březen', 'Duben', 'Květen',
+ 'Červen', 'Červenec', 'Srpen', 'Září',
+ 'Říjen', 'Listopad', 'Prosinec'],
+ ['Pondělí','Úterý','Středa','Čtvrtek','Pátek','Sobota', 'Neděle']],
+'Czech-short' :
+ [['Leden', 'Únor', 'Březen', 'Duben', 'Květen',
+ 'Červen', 'Červenec', 'Srpen', 'Září',
+ 'Říjen', 'Listopad', 'Prosinec'],
+ ['Po', 'Út', 'St', 'Čt', 'Pá', 'So', 'Ne']],
+# Croatian by daweed
+'Croatian' :
+ [['Siječanj', 'Veljača', 'Ožujak', 'Travanj', 'Svibanj',
+ 'Lipanj', 'Srpanj', 'Kolovoz', 'Rujan',
+ 'Listopad', 'Studeni', 'Prosinac'],
+ ['Ponedjeljak','Utorak','Srijeda','Četvrtak','Petak','Subota', 'Nedjelja']],
+
+'Dutch' :
+ [['Januari', 'Februari', 'Maart', 'April',
+ 'Mei', 'Juni', 'Juli', 'Augustus', 'September',
+ 'Oktober', 'November', 'December'],
+ ['Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag','Zaterdag', 'Zondag']],
+# Dutch by "Christoph Schäfer" <christoph-schaefer@gmx.de>
+'English' :
+ [['January', 'February', 'March', 'April',
+ 'May', 'June', 'July', 'August', 'September',
+ 'October', 'November', 'December'],
+ ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday', 'Sunday']],
+'English-short' :
+ [['January', 'February', 'March', 'April', 'May',
+ 'June', 'July', 'August', 'September', 'October',
+ 'November', 'December'],
+ ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']],
+'Finnish' :
+ [['Tammikuu', 'Helmikuu', 'Maaliskuu', 'Huhtikuu',
+ 'Toukokuu', 'Kesäkuu', 'Heinäkuu', 'Elokuu', 'Syyskuu',
+ 'Lokakuu', 'Marraskuu', 'Joulukuu'],
+ ['ma','ti','ke','to','pe','la', 'su']],
+'French':
+ [['Janvier', u'F\xe9vrier', 'Mars', 'Avril',
+ 'Mai', 'Juin', 'Juillet', u'Ao\xfbt', 'Septembre',
+ 'Octobre', 'Novembre', u'D\xe9cembre'],
+ ['Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi','Dimanche']],
+'German' :
+ [['Januar', 'Februar', u'M\xe4rz', 'April',
+ 'Mai', 'Juni', 'Juli', 'August', 'September',
+ 'Oktober', 'November', 'Dezember'],
+ ['Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag','Sonntag']],
+'German (Austrian)' :
+ [[u'J\xe4nner', 'Feber', u'M\xe4rz', 'April',
+ 'Mai', 'Juni', 'Juli', 'August', 'September',
+ 'Oktober', 'November', 'Dezember'],
+ ['Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag','Sonntag']],
+# Hungarian by Gergely Szalay szalayg@gmail.com
+'Hungarian' :
+ [['Január', 'Február', 'Március', 'Április',
+ 'Május', 'Június', 'Július', 'Augusztus', 'Szeptember',
+ 'Október', 'November', 'December'],
+ ['Hétfő','Kedd','Szerda','Csütörtök','Péntek','Szombat','Vasárnap']],
+'Italian' :
+ [['Gennaio', 'Febbraio', 'Marzo', 'Aprile',
+ 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre',
+ 'Ottobre', 'Novembre', 'Dicembre'],
+ [u'Luned\xec', u'Marted\xec', u'Mercoled\xec', u'Gioved\xec', u'Venerd\xec', 'Sabato', 'Domenica']],
+# Norwegian by Joacim Thomassen joacim@net.homelinux.org
+'Norwegian' :
+ [['Januar', 'Februar','Mars', 'April','Mai', 'Juni','Juli', 'August','September', 'Oktober', 'November', 'Desember'],
+ ['Mandag', 'Tirsdag','Onsdag', 'Torsdag','Fredag', 'Lørdag','Søndag']],
+# Polish by "Łukasz [DeeJay1] Jernaś" <deejay1@nsj.srem.pl>
+'Polish' :
+ [['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj',
+ 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień',
+ 'Październik', 'Listopad', 'Grudzień'],
+ ['Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota', 'Niedziela']],
+'Portuguese' :
+ [['Janeiro', 'Fevereiro', u'Mar\xe7o', 'Abril',
+ 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro',
+ 'Outubro', 'Novembro', 'Dezembro'],
+ ['Segunda-feira', u'Ter\xe7a-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', u'S\xe1bado', 'Domingo']],
+# Romanian by Costin Stroie <costinstroie@eridu.eu.org>
+'Romanian' :
+ [['Ianuarie', 'Februarie', 'Martie', 'Aprilie',
+ 'Mai', 'Iunie', 'Iulie', 'August', 'Septembrie',
+ 'Octombrie', 'Noiembrie', 'Decembrie'],
+ ['Luni','Mar\xc8\x9bi','Miercuri','Joi','Vineri','S\xc3\xa2mb\xc4\x83t\xc4\x83', 'Duminic\xc4\x83']],
+'Russian' :
+ [['Январь', 'Февраль', 'Март', 'Апрель',
+ 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь',
+ 'Октябрь', 'Ноябрь', 'Декабрь'],
+ ['Понедельник','Вторник','Среда','Четверг','Пятница','Суббота', 'Воскресенье']],
+'Slovak' :
+ [['Január', 'Február', 'Marec', 'Apríl',
+ 'Máj', 'Jún', 'Júl', 'August', 'September',
+ 'Október', 'November', 'December'],
+ ['Pondelok','Utorok','Streda','Štvrtok','Piatok','Sobota', 'Nedeľa']],
+'Slovak-short' :
+ [['Január', 'Február', 'Marec', 'Apríl',
+ 'Máj', 'Jún', 'Júl', 'August', 'September',
+ 'Október', 'November', 'December'],
+ ['Po','Ut','St','Št','Pi','So', 'Ne']],
+'Spanish' :
+ [['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo',
+ 'Junio', 'Julio', 'Agosto', 'Septiembre',
+ 'Octubre', 'Noviembre', 'Diciembre'],
+ ['Lunes', 'Martes', u'Mi\xe9rcoles', 'Jueves', 'Viernes', u'S\xe1bado', 'Domingo']],
+'Swedish' :
+ [['Januari', 'Februari','Mars', 'April','Maj', 'Juni','Juli', 'Augusti','September', 'Oktober', 'November', 'December'],
+ ['Måndag', 'Tisdag','Onsdag', 'Torsdag','Fredag', 'Lördag','Söndag']]
+}
+
+
+from math import sqrt
+
+class ScCalendar:
+ """ Parent class for all calendar types """
+
+ def __init__(self, year, months=[], firstDay=calendar.SUNDAY, drawSauce=True, sepMonths='/', lang='English'):
+ """ Setup basic things """
+ # params
+ self.drawSauce = drawSauce # draw supplementary image?
+ self.year = year
+ self.months = months
+ self.lang = lang
+ # day order
+ self.dayOrder = localization[self.lang][1]
+ if firstDay == calendar.SUNDAY:
+ dl = self.dayOrder[:6]
+ dl.insert(0, self.dayOrder[6])
+ self.dayOrder = dl
+ self.mycal = calendar.Calendar(firstDay)
+ self.layerImg = 'Calendar image'
+ self.layerCal = 'Calendar'
+ self.pStyleDate = "Date" # paragraph styles
+ self.pStyleWeekday = "Weekday"
+ self.pStyleMonth = "Month"
+ self.pStyleWeekNo = "WeekNo"
+ self.masterPage = "Weekdays"
+ self.sepMonths = sepMonths
+ # settings
+ self.firstPage = True # create only 2nd 3rd ... pages. No 1st one.
+ calendar.setfirstweekday(firstDay)
+ progressTotal(len(months))
+
+ def setupDocVariables(self):
+ """ Compute base metrics here. Page layout is bordered by margins and
+ virtually divided by golden mean 'cut' in the bottom. The calendar is
+ in the bottom part - top is occupied with empty image frame. """
+ page = getPageSize()
+ self.pagex = page[0]
+ self.pagey = page[1]
+ marg = getPageMargins()
+ # See http://docs.scribus.net/index.php?lang=en&page=scripterapi-page#-getPageMargins
+ self.margint = marg[0]
+ self.marginl = marg[1]
+ self.marginr = marg[2]
+ self.marginb = marg[3]
+ self.width = self.pagex - self.marginl - self.marginr
+ self.height = self.pagey - self.margint - self.marginb
+
+ def goldenMean(self, aSize):
+ """ Taken from samples/golden-mean.py."""
+ return aSize * ((sqrt(5) - 1)/2)
+
+ def applyTextToFrame(self, aText, aFrame):
+ """ Insert the text with style. """
+ setText(aText, aFrame)
+ setStyle(self.pStyleDate, aFrame)
+
+ def createCalendar(self):
+ """ Walk through months dict and call monthly sheet """
+ if not newDocDialog():
+ return 'Create a new document first, please'
+ createParagraphStyle(name=self.pStyleDate, alignment=ALIGN_RIGHT)
+ createParagraphStyle(name=self.pStyleWeekday, alignment=ALIGN_RIGHT)
+ createParagraphStyle(name=self.pStyleMonth)
+ createParagraphStyle(name=self.pStyleWeekNo, alignment=ALIGN_RIGHT)
+ originalUnit = getUnit()
+ setUnit(UNIT_POINTS)
+ self.setupDocVariables()
+ if self.drawSauce:
+ createLayer(self.layerImg)
+ createLayer(self.layerCal)
+ self.setupMasterPage()
+ run = 0
+ for i in self.months:
+ run += 1
+ progressSet(run)
+ cal = self.mycal.monthdatescalendar(self.year, i + 1)
+ self.createMonthCalendar(i, cal)
+ setUnit(originalUnit)
+ return None
+
+ def createLayout(self):
+ """ Create the page and optional bells and whistles around """
+ self.createPage()
+ if self.drawSauce:
+ setActiveLayer(self.layerImg)
+ self.createImage()
+ setActiveLayer(self.layerCal)
+
+ def createPage(self):
+ """ Wrapper to the new page with layers """
+ if self.firstPage:
+ self.firstPage = False
+ newPage(-1, self.masterPage) # create a new page using the masterPage
+ deletePage(1) # now it's safe to delete the first page
+ gotoPage(1)
+ return
+ newPage(-1, self.masterPage)
+
+class ScEventCalendar(ScCalendar):
+ """ Parent class for event
+ (horizontal event, vertical event) calendar types """
+
+ def __init__(self, year, months = [], firstDay = calendar.SUNDAY, drawSauce=True, sepMonths='/', lang='English'):
+ ScCalendar.__init__(self, year, months, firstDay, drawSauce, sepMonths, lang)
+
+ def printMonth(self, cal, month, week):
+ """ Print the month name(s) """
+ if week[6].day < 7:
+ if (week == cal[len(cal)-1]):
+ self.createHeader(localization[self.lang][0][month] + self.sepMonths + localization[self.lang][0][(month+1)%12])
+ elif ((month-1) not in self.months):
+ self.createHeader(localization[self.lang][0][(month-1)%12] + self.sepMonths + localization[self.lang][0][month])
+ else:
+ self.createHeader(localization[self.lang][0][month])
+
+ def createMonthCalendar(self, month, cal):
+ """ Draw one week calendar per page """
+ for week in cal:
+ # Avoid duplicate week around the turn of the months:
+ # Only include week:
+ # * If it's not the first week in a month, or, if it is:
+ # * If it starts on the first weekday
+ # * If the month before it isn't included
+ if (week != cal[0]) or (week[0].day == 1) or ((month-1) not in self.months):
+ self.createLayout()
+ self.printMonth(cal, month, week)
+ self.printWeekNo(week)
+
+ for day in week:
+ self.printDay(day)
+
+class ScHorizontalEventCalendar(ScEventCalendar):
+ """ One day = one row calendar. I suggest LANDSCAPE orientation.\
+ One week per page."""
+
+ def __init__(self, year, months = [], firstDay = calendar.SUNDAY, drawSauce=True, sepMonths='/', lang='English'):
+ ScEventCalendar.__init__(self, year, months, firstDay, drawSauce, sepMonths, lang)
+
+ def setupDocVariables(self):
+ """ Compute base metrics here. Page layout is bordered by margins and
+ virtually divided by golden mean 'cut' in the bottom. The calendar is
+ in the bottom part - top is occupied with empty image frame. """
+ # golden mean
+ ScCalendar.setupDocVariables(self)
+ self.gmean = self.width - self.goldenMean(self.width) + self.marginl
+ # calendar size = gmean
+ # rows and cols
+ self.rowSize = self.height / 8
+
+ def printWeekNo(self, week):
+ """ Dummy for now
+ (for this type of calendar - see ScVerticalEventCalendar) """
+ return
+
+ def printDay(self, j):
+ """ Print a given day """
+ cel = createText(self.gmean + self.marginl,
+ self.margint + (1 + (j.weekday()-calendar.firstweekday())%7) * self.rowSize,
+ self.width - self.gmean, self.rowSize)
+ setText(str(j.day), cel)
+ setStyle(self.pStyleDate, cel)
+
+ def createHeader(self, monthName):
+ """ Draw calendar header: Month name """
+ cel = createText(self.gmean + self.marginl, self.margint,
+ self.width - self.gmean, self.rowSize)
+ setText(monthName, cel)
+ setStyle(self.pStyleMonth, cel)
+
+ def createImage(self):
+ """ Wrapper for everytime-the-same image frame. """
+ if self.drawSauce:
+ createImage(self.marginl, self.margint, self.gmean, self.height)
+
+ def setupMasterPage(self):
+ """ Create a master page (not used for this type of calendar """
+ createMasterPage(self.masterPage)
+ closeMasterPage()
+
+class ScVerticalCalendar(ScCalendar):
+ """ Parent class for vertical
+ (classic, vertical event) calendar types """
+
+ def __init__(self, year, months = [], firstDay = calendar.SUNDAY, drawSauce=True, sepMonths='/', lang='English'):
+ ScCalendar.__init__(self, year, months, firstDay, drawSauce, sepMonths, lang)
+
+ def setupDocVariables(self):
+ """ Compute base metrics here. Page layout is bordered by margins and
+ virtually divided by golden mean 'cut' in the bottom. The calendar is
+ in the bottom part - top is occupied with empty image frame. """
+ # gloden mean
+ ScCalendar.setupDocVariables(self)
+ self.gmean = self.height - self.goldenMean(self.height) + self.margint
+ # calendar size
+ self.calHeight = self.height - self.gmean + self.margint
+ # rows and cols
+ self.rowSize = self.gmean / 8
+ self.colSize = self.width / 7
+
+ def setupMasterPage(self):
+ """ Draw invariant calendar header: Days of the week """
+ createMasterPage(self.masterPage)
+ editMasterPage(self.masterPage)
+ setActiveLayer(self.layerCal)
+ rowCnt = 0
+ for j in self.dayOrder: # days
+ cel = createText(self.marginl + rowCnt*self.colSize,
+ self.calHeight + self.rowSize,
+ self.colSize, self.rowSize)
+ setText(j, cel)
+ setStyle(self.pStyleWeekday, cel)
+ rowCnt+=1
+ closeMasterPage()
+
+ def createHeader(self, monthName):
+ """ Draw calendar header: Month name """
+ header = createText(self.marginl, self.calHeight, self.width, self.rowSize)
+ setText(monthName, header)
+ setStyle(self.pStyleMonth, header)
+
+ def createImage(self):
+ """ Wrapper for everytime-the-same image frame. """
+ if self.drawSauce:
+ createImage(self.marginl, self.margint,
+ self.width, self.calHeight - self.margint)
+
+class ScClassicCalendar(ScVerticalCalendar):
+ """ Calendar matrix creator itself. I suggest PORTRAIT orientation.
+ One month per page."""
+
+ def __init__(self, year, months = [], firstDay = calendar.SUNDAY, drawSauce=True, sepMonths='/', lang='English'):
+ ScVerticalCalendar.__init__(self, year, months, firstDay, drawSauce, sepMonths, lang)
+
+ def createMonthCalendar(self, month, cal):
+ """ Create a page and draw one month calendar on it """
+ self.createLayout()
+ self.createHeader(localization[self.lang][0][month])
+ rowCnt = 2
+ for week in cal:
+ colCnt = 0
+ for day in week:
+ cel = createText(self.marginl + colCnt * self.colSize,
+ self.calHeight + rowCnt * self.rowSize,
+ self.colSize, self.rowSize)
+ colCnt += 1
+ if day.month == month + 1:
+ setText(str(day.day), cel)
+ setStyle(self.pStyleDate, cel)
+ rowCnt += 1
+
+class ScVerticalEventCalendar(ScVerticalCalendar, ScEventCalendar):
+ """ One day = one column calendar. I suggest LANDSCAPE orientation.\
+ One week per page."""
+
+ def __init__(self, year, months = [], firstDay = calendar.SUNDAY, drawSauce=True, sepMonths='/', lang='English'):
+ ScVerticalCalendar.__init__(self, year, months, firstDay, drawSauce, sepMonths, lang)
+ ScEventCalendar.__init__(self, year, months, firstDay, drawSauce, sepMonths, lang)
+
+ def printDay(self, j):
+ """ Print a given day """
+ cel = createText(self.marginl + ((j.weekday()-calendar.firstweekday())%7)*self.colSize,
+ self.calHeight + self.rowSize,
+ self.colSize/5, self.rowSize)
+ setText(str(j.day), cel)
+ setStyle(self.pStyleDate, cel)
+
+ def printWeekNo(self, week):
+ """ Print the week number for the given week"""
+ weekCel = createText(self.marginl, self.calHeight, self.width, self.rowSize)
+ # Week number: of this week's Thursday.
+ # See http://docs.python.org/library/datetime.html#datetime.date.isocalendar
+ # Note that week calculation isn't perfectly universal yet:
+ # http://en.wikipedia.org/wiki/Week_number#Week_number
+ setText(str(week[(calendar.THURSDAY-calendar.firstweekday())%7].isocalendar()[1]), weekCel)
+ setStyle(self.pStyleWeekNo, weekCel)
+
+class TkCalendar(Frame):
+ """ GUI interface for Scribus calendar wizard.
+ It's ugly and very simple. I can say I hate Tkinter :-/"""
+
+ def __init__(self, master=None):
+ """ Setup the dialog """
+ # reference to the localization dictionary
+ self.key = 'English'
+ Frame.__init__(self, master)
+ self.grid()
+ self.master.resizable(0, 0)
+ self.master.title('Scribus Calendar Wizard')
+ #define widgets
+ self.statusVar = StringVar()
+ self.statusLabel = Label(self, textvariable=self.statusVar)
+ self.statusVar.set('Select Options and Values')
+ # langs
+ # change the height = to match number of langs.
+ self.langLabel = Label(self, text='Select language:')
+
+ self.langFrame = Frame(self)
+ self.langFrame.pack()
+ self.langScrollbar = Scrollbar(self.langFrame)
+ self.langScrollbar.pack(fill=Y, side=RIGHT)
+ self.langListbox = Listbox(self.langFrame, selectmode=SINGLE, height=10, yscrollcommand=self.langScrollbar.set)
+ self.langListbox.pack(fill=X,side=LEFT)
+ self.langScrollbar.config(command=self.langListbox.yview)
+
+ keys = localization.keys()
+ keys.sort()
+ for i in keys:
+ self.langListbox.insert(END, i)
+ self.langButton = Button(self, text='Change language', command=self.languageChange)
+ # calendar type
+ self.typeLabel = Label(self, text='Calendar type')
+ self.typeVar = IntVar()
+ self.typeClRadio = Radiobutton(self, text='Classic', variable=self.typeVar, value=0)
+ self.typeEvRadio = Radiobutton(self, text='Event (Horizontal)', variable=self.typeVar, value=1)
+ self.typeVERadio = Radiobutton(self, text='Event (Vertical)', variable=self.typeVar, value=2)
+ # start of week
+ self.weekStartsLabel = Label(self, text='Week begins with:')
+ self.weekVar = IntVar()
+ self.weekMondayRadio = Radiobutton(self, text='Mon', variable=self.weekVar, value=calendar.MONDAY)
+ self.weekSundayRadio = Radiobutton(self, text='Sun', variable=self.weekVar, value=calendar.SUNDAY)
+ # year
+ self.yearLabel = Label(self, text='Year:')
+ self.yearVar = StringVar()
+ self.yearEntry = Entry(self, textvariable=self.yearVar, width=4)
+ self.wholeYearLabel = Label(self, text='Whole year:')
+ self.wholeYear = IntVar()
+ self.wholeYearCheck = Checkbutton(self, command=self.setWholeYear, variable=self.wholeYear)
+ # months
+ self.monthLabel = Label(self, text='Months:')
+ self.monthListbox = Listbox(self, selectmode=MULTIPLE, height=12)
+ # layout stuff
+ self.imageLabel = Label(self, text='Draw Image Frame:')
+ self.imageVar = IntVar()
+ self.imageCheck = Checkbutton(self, variable=self.imageVar)
+ # Months separator
+ self.sepMonthsLabel = Label(self, text='Months separator:')
+ self.sepMonthsVar = StringVar()
+ self.sepMonthsEntry = Entry(self, textvariable=self.sepMonthsVar, width=4)
+ # closing/running
+ self.okButton = Button(self, text="OK", width=6, command=self.okButonn_pressed)
+ self.cancelButton = Button(self, text="Cancel", command=self.quit)
+ # setup values
+ self.weekMondayRadio.select()
+ self.typeClRadio.select()
+ self.yearVar.set(str(datetime.date(1, 1, 1).today().year))
+ self.sepMonthsVar.set('/')
+ self.imageCheck.select()
+ # make layout
+ self.columnconfigure(0, pad=6)
+ currRow = 0
+ self.statusLabel.grid(column=0, row=currRow, columnspan=4)
+ currRow += 1
+ self.langLabel.grid(column=0, row=currRow, sticky=W)
+ self.monthLabel.grid(column=3, row=currRow, sticky=W)
+ currRow += 1
+ self.langFrame.grid(column=0, row=currRow, rowspan=6, sticky=N)
+ self.typeLabel.grid(column=1, row=currRow, sticky=E)
+ self.typeClRadio.grid(column=2, row=currRow, sticky=W)
+ self.monthListbox.grid(column=3, row=currRow, rowspan=8)
+ currRow += 1
+ self.typeEvRadio.grid(column=2, row=currRow, sticky=W)
+ currRow += 1
+ self.typeVERadio.grid(column=2, row=currRow, sticky=W)
+ currRow += 1
+ self.weekStartsLabel.grid(column=1, row=currRow, sticky=N+E)
+ self.weekMondayRadio.grid(column=2, row=currRow, sticky=N+W)
+ currRow += 1
+ self.weekSundayRadio.grid(column=2, row=currRow, sticky=N+W)
+ currRow += 1
+ self.yearLabel.grid(column=1, row=currRow, sticky=N+E)
+ self.yearEntry.grid(column=2, row=currRow, sticky=N+W)
+ currRow += 1
+ self.wholeYearLabel.grid(column=1, row=currRow, sticky=N+E)
+ self.wholeYearCheck.grid(column=2, row=currRow, sticky=N+W)
+ currRow += 1
+ self.imageLabel.grid(column=1, row=currRow, sticky=N+E)
+ self.imageCheck.grid(column=2, row=currRow, sticky=N+W)
+ self.langButton.grid(column=0, row=currRow)
+ currRow += 1
+ self.sepMonthsLabel.grid(column=1, row=currRow, sticky=N+E)
+ self.sepMonthsEntry.grid(column=2, row=currRow, sticky=N+W)
+ currRow += 3
+ self.rowconfigure(currRow, pad=6)
+ self.okButton.grid(column=1, row=currRow, sticky=E)
+ self.cancelButton.grid(column=2, row=currRow, sticky=W)
+ # fill the values
+ self.realLangChange()
+
+ def languageChange(self, lang='English'):
+ """ Called by Change button. Get language list value and
+ call real re-filling. """
+ ix = self.langListbox.curselection()
+ if len(ix)==0:
+ self.statusVar.set('Select a language, please')
+ return
+ self.realLangChange(lang=self.langListbox.get(ix[0]))
+
+ def realLangChange(self, lang='English'):
+ """ Real widget setup. Ot takes values from localization dictionary.
+ [0] = months, [1] Days """
+ self.key = lang
+ self.monthListbox.delete(0, END)
+ self.wholeYear.set(0)
+ for i in localization[lang][0]:
+ self.monthListbox.insert(END, i)
+
+ def setWholeYear(self):
+ """ All/none months selection. It's called after "Whole year" check button
+ click. """
+ if self.wholeYear.get() == 1:
+ self.monthListbox.selection_set(0, END)
+ else:
+ self.monthListbox.selection_clear(0, END)
+
+ def okButonn_pressed(self):
+ """ User variables testing and preparing """
+ # year
+ try:
+ year = self.yearVar.get().strip()
+ if len(year) != 4:
+ raise ValueError
+ year = int(year, 10)
+ except ValueError:
+ self.statusVar.set('Year must be in the "YYYY" format e.g. 2005.')
+ return
+ # months
+ selMonths = self.monthListbox.curselection()
+ if len(selMonths) == 0:
+ self.statusVar.set('At least one month must be selected.')
+ return
+ months = []
+ for i in selMonths:
+ months.append(int(i))
+ # draw images etc.
+ if self.imageVar.get() == 0:
+ draw = False
+ else:
+ draw = True
+ # create calendar (finally)
+ if self.typeVar.get() == 0:
+ cal = ScClassicCalendar(year, months, self.weekVar.get(), draw, self.sepMonthsVar.get(), self.key)
+ elif self.typeVar.get() == 1:
+ cal = ScHorizontalEventCalendar(year, months, self.weekVar.get(), draw, self.sepMonthsVar.get(), self.key)
+ else:
+ cal = ScVerticalEventCalendar(year, months, self.weekVar.get(), draw, self.sepMonthsVar.get(), self.key)
+ self.master.withdraw()
+ err = cal.createCalendar()
+ if err != None:
+ self.master.deiconify()
+ self.statusVar.set(err)
+ else:
+ self.quit()
+
+ def quit(self):
+ self.master.destroy()
+
+
+def main():
+ """ Application/Dialog loop with Scribus sauce around """
+ try:
+ statusMessage('Running script...')
+ progressReset()
+ root = Tk()
+ app = TkCalendar(root)
+ root.mainloop()
+ finally:
+ if haveDoc():
+ redrawAll()
+ statusMessage('Done.')
+ progressReset()
+
+if __name__ == '__main__':
+ main()
+
diff --git a/scribus/plugins/scriptplugin/scripts/ChangeLog b/scribus/plugins/scriptplugin/scripts/ChangeLog
new file mode 100644
index 0000000..c3f8e0f
--- /dev/null
+++ b/scribus/plugins/scriptplugin/scripts/ChangeLog
@@ -0,0 +1,181 @@
+20061016 v 0.8.2tk
+ A one liner change by Jean Ghali to line #734 to add the extra parameter missing.
+20051124 v0.8tk final:
+ Cleaned up the checkbox labels and layout.
+
+20051121 v0.8tk preview 3:
+ Calls the new Scribus zoomDocument() function to make the completed font
+ sample document fit in Scribus window.
+
+ Grey out "Start page number count from first page" when "Print TOC" is
+ not checked as without a table of contents the first page would always
+ start on the same page number making this option irrelevant.
+
+20051120 v0.8tk preview 2:
+ Replaced the newDoc() with newDocument(). Have not put any fallback code
+ for use with earlier Scribus versions.
+
+ When using double sided option we now make use of Scribus ability to display
+ pages side by side as default. You may need to zoom out to view the
+ complete document width. This is because currently there is no way of setting
+ "Fit To Page" from the Scripter.
+
+20050902 v0.8tk preview 1:
+ Rearanged the initialisation. If no fonts are found for the Table of
+ Contents, page numbers and font sample labels, the script shows a
+ message box listing the problem and a possible solution as well as a message
+ to the console.
+
+ A Scribus messagebox alerts the user if Tkinter is not found. Previously
+ this message was only printed to the console.
+
+ Now able to do a dummy run to calculate and report the amount of samples
+ that will fit on a page. This enables the script to correctly calculate
+ how many sheets will be required. Previously it was always assumed that
+ there would be 3 sample blocks on a sheet. This is now not always the case.
+
+ Added menu. Also added "about" and "settings" dialogs.
+
+ Sample rows can be selected or unselected to save on paper. The settings are
+ automatically saved when changed and can be set as user defaults.
+
+ User can choose to have page numbers count from first page of the toc instead
+ of the first page of samples. This can be helpful if wanting to quickly look
+ up a font in the toc and then using the Scribus page navigator dialog to go to
+ the actual page on the screen to view it without printing it out.
+
+ Added initial support for a sample paragraph. The sample paragraph defaults
+ to "off" due to the amount of space it uses on the page.
+
+ Some widgets read their defaults from a config dictionary.
+
+ Many code cleanups. Classes used for settings storage have been replaced with
+ dictionaries to make it easier for users to customise.
+
+###################################################
+
+20050930 v0.7.5tk
+ Fixed bug in table of contents. TOC rows value was not being honoured.
+ Would create an unrequired blank headed toc page when the TOC rows count setting
+ matched the amount of samples selected.
+
+20050814 v0.7.4tk
+ Now updates the Scribus Progress Bar (one increment for each font drawn).
+
+20050813 v0.7.3tk
+ Fix typo in exception code.
+ Modified case of some script variables to make compatible with changes
+ in Scribus 1.3 scriptor.
+ Removed the reduntant "self.master.maxsize(1, 1)" from the application class.
+
+20050104 v0.7.2tk
+ More cleanups in font preview code. If a font cannot be displayed
+ then the preview panel is cleared. Removed many error messages returned
+ to the console.
+
+20050103 v0.7.1tk
+ Removed discontinued email address
+
+20041230 v0.7tk
+ Added a preview panel so user can see a sample of what a font may look like
+ before selecting it to use.
+ Detects failure of Python Imaging Library module to load and tests for the ability to
+ write to .scribus folder then disables preview if necessary.
+ Incorporated Craig Ringers boilerplate and Scribus function case changes.
+ Put labels on the left and right listboxes describing what they do.
+ Listboxes now get focus when selected with the mouse. This allows Up Down
+ keys to be used to scroll through font names.
+ When selecting a single item in a listbox, the font highlighted will be
+ displayed in a panel.
+ Some function names have changed and some docstrings added.
+ The main window should no longer be expandable.
+
+20040224 v0.6.1
+ A bug fix was introduced to Scribus CVS on 20040223 that affected the text
+ frames. This version has an adjusted height and position of some text frames
+ to make the samples correctly fit inside them again.
+
+20040212 v0.6 final
+ Fixed bug that stopped multiple selection move from working properly.
+ More code cleanups.
+ Adjusted the button positions.
+ Added logic to gray out "item up" and "item down" buttons when not appropriate.
+ Enhanced the "move left" and "move right" button gray out code.
+ Fixed a problem when double clicking on a multiple selection of rows.
+ Small adjustments and fixes to the layouts.
+
+20030130 v0.6 preview 5
+ Now contains a list of acceptable proportional and fixed width fonts that are needed for
+ the TOC and font sample labels. If a match is not found with the installed font list available to Scribus
+ then an error message is dumped to the console with a list of the required fonts for the user to get. The
+ script will continue to run with whatever font happens be be set as default in Scribus.
+ Fixed broken horizontal line drawing code.
+ Various size adjustments to text frames that were drawing outside of margin area.
+
+20030129 v0.6 preview 4
+ Rewritten useSelection function. Now measures the available space left on page before placing the
+ sample block. It is now possible to select the sample lines to print by commenting out rows in
+ the drawSampleBlock() function and if there is space then more samples will be placed on the page.
+ Renamed some functions.
+ Made some small adjustments to the text frame dimensions.
+
+20040126 v0.6 preview 3
+ Added double sided paper handling.
+ Added binding offsets.
+ Left hand pane allows multiple selection again. Shift and mouse drag will select a block,
+ hold Control plus click to highlight single items. Press '>' button to move the seelcted group to the
+ right hand pane.
+ More code cleanups.
+ removed pound sign from sample string. It was causing errors with Python V2.3 thanks MrB
+ Changed default sans font to "Nimbus Sans L Regular" instead of "Arial"
+
+20040123 v0.6 preview 2
+ fixed the extra page bug introduced in v0.6 preview 1
+ Changed the 36 point font to 32 point. this improves the layout of the samples.
+
+20040120 v0.6 preview 1
+ Start adding optional page numbers.
+ Start adding optional table of contents.
+ Improve paper size variables format.
+ More code cleanups.
+ If a second (or more) font list was created with the script then it would be impossible to
+ view anything other than the most recent document in Scribus - fixed
+
+20040121 v0.5a
+ Small change to fix non display of earlier font sample documents still open in Scribus
+ if the script is run again.
+
+20040112 v0.5
+ Added SetRedraw to speed up page generation.
+ Added status bar to display the quantity of fonts available, how many are selected
+ and how many pages will be needed.
+ Added a paper size selector.
+
+20040107 v0.4
+ More cleanups in the main page generator loop
+ Added 6 point sample
+ Left list box now sorts correctly when moving individual items back to it
+ More adjustments to text layouts
+
+20040106 v0.3a
+ fixed page creep bug
+
+20040106 v0.3
+ Put each text string into its own text frame and put in separator lines
+ Prints the font size as part of the test string
+ Can crudely set A4 or US Letter size paper by uncommenting the appropriate
+ 2 lines in useselection()
+ changing this just adjusts the position of the samples on the page for the change
+ in paper length.
+ Some code clean ups.
+
+20040105 v0.2
+ Rearranged the buttons. Put in Franz's fix. Thanks Franz.
+ Put in some more sample lines including the standard alphabet characters.
+
+20040105 v0.1a
+ Added a double click to select font in font selector.
+ Fixes to some button logic. Gray out as required.
+
+20040104 v0.1
+ First release
diff --git a/scribus/plugins/scriptplugin/scripts/ColorChart.py b/scribus/plugins/scriptplugin/scripts/ColorChart.py
new file mode 100644
index 0000000..46946d3
--- /dev/null
+++ b/scribus/plugins/scriptplugin/scripts/ColorChart.py
@@ -0,0 +1,350 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+"""
+ABOUT THIS SCRIPT:
+
+ColorChart.py allows a user to create color charts with all
+the colors of a given scribus document.
+It generates a color field for each color and a description
+of the color, containing the color name, the CMYK values and
+the RGB values.
+
+If there is a document opened in scribus, ColorChart uses this
+document as color source and creates a new document with the
+color chart.
+If there is no document opened in scribus, ColorChart displays
+a file open dialog to allow the user to chose a scribus file
+to generate a colorchart of.
+You will be asked to give a name for the color chart. This name
+will be displayed in the pages headlines.
+############################
+
+LICENSE:
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+Author: Sebastian Stetter
+please report bugs to: scribusscript@sebastianstetter.de
+"""
+from __future__ import division
+import sys
+__version__=1.1
+try:
+ # Please do not use 'from scribus import *' . If you must use a 'from import',
+ # Do so _after_ the 'import scribus' and only import the names you need, such
+ # as commonly used constants.
+ import scribus
+except ImportError,err:
+ print "This Python script is written for the Scribus scripting interface."
+ print "It can only be run from within Scribus."
+ sys.exit(1)
+
+####################
+# IMPORTS GO HERE #
+####################
+
+COLOR_FIELD_HEIGHT=25
+#space between colorfields
+HSPACE=5
+VSPACE=4
+#space for header and footer
+HEADERSIZE = 10
+FOOTERSIZE = 5
+TEXT_BOX_WIDTH = 50
+global pageTitle
+pageTitle="COLOR CHART"
+
+def drawHeaderFooter(pagetitle):
+ """draw some info on the pages"""
+ # get page size
+ pageSize=scribus.getPageSize()
+ pageWidth=pageSize[0]
+ pageHeight=pageSize[1]
+ #pageMargins
+ pageMargins=scribus.getPageMargins()
+ topMargin=pageMargins[0]
+ leftMargin=pageMargins[1]
+ rightMargin=pageMargins[2]
+ bottomMargin=pageMargins[3]
+
+ #create textbox and insert text for header
+ textbox=scribus.createText(leftMargin, topMargin, pageWidth-leftMargin-rightMargin, HEADERSIZE)
+ #set proper font size and alignment
+ scribus.setFontSize(18, textbox)
+ scribus.setTextAlignment(scribus.ALIGN_CENTERED, textbox)
+ #load the string into the textbox
+ headerstring=pagetitle
+ scribus.insertText(headerstring, 0, textbox)
+
+ #create textbox and insert text for footer
+ textbox=scribus.createText(leftMargin, pageHeight-bottomMargin-FOOTERSIZE, pageWidth-leftMargin-rightMargin, FOOTERSIZE)
+ #set proper font size and alignment
+ scribus.setFontSize(9, textbox)
+ scribus.setTextAlignment(scribus.ALIGN_LEFT, textbox)
+ #load the string into the textbox
+ footerstring="Created using ColorChart.py V %s script for Scribus by Sebastian Stetter - http://www.sebastianstetter.de" % str(__version__)
+ scribus.insertText(footerstring, 0, textbox)
+
+
+def getSpotColors():
+ """ Get spot colors from an original document.
+ Must be called after getColorsFromDocument().
+ """
+ ret = {}
+ for color in scribus.getColorNames():
+ ret[color] = scribus.isSpotColor(color)
+ return ret
+
+
+def getColorsFromDocument():
+ """gets colors from opend document. if there is no document, display dialog to chose a file. returns a list[name,c,m,y,k]"""
+ def getColors():
+ """gets the colors and returns a list[name,c,m,y,k]"""
+ colorNames=scribus.getColorNames()
+ list=[]
+ scribus.statusMessage("Reading Colors...")
+ stepsTotal=len(colorNames)
+ scribus.progressTotal(stepsTotal)
+ steps=0
+ for name in colorNames:
+ color=scribus.getColor(name)
+ listitem=[name, color[0], color[1], color[2], color[3]]
+ list.append(listitem)
+ #update progress bar
+ steps=steps+1
+ scribus.progressSet(steps)
+ return list
+
+ #check if we have a document - otherwise display open file dialog
+ if scribus.haveDoc() == 1:
+ pass
+ list=getColors()
+ return list
+ else:
+ pass
+ #display file open dialog
+ file=scribus.fileDialog("ColorChart by Sebastian Stetter", 'Scribus files(*.sla *.SLA *.sla.gz *.SLA.GZ)')
+ #open file
+ try:
+ scribus.openDoc(file)
+ except:
+ scribus.messageBox("ColorChart by Sebastian Stetter", "could not open file")
+ sys.exit()
+ list=getColors()
+ return list
+
+def prepareDocument():
+ """creates the new document, sets up colors """
+ colorList = getColorsFromDocument()
+ spotDict = getSpotColors()
+ scribus.statusMessage("Preparing new document...")
+ scribus.newDocument(scribus.PAPER_A4, (15,15, 20, 20), scribus.PORTRAIT, 1, scribus.UNIT_POINTS, scribus.PAGE_1, 0, 1)
+ scribus.setUnit(scribus.UNIT_MILLIMETERS)
+ #delete existing colors
+ cols = scribus.getColorNames()
+ for col in cols:
+ scribus.deleteColor(col, "None")
+
+ #create our new colors
+ for color in colorList:
+ cname=color[0]
+ c = int(color[1])
+ m = int(color[2])
+ y = int(color[3])
+ k = int(color[4])
+ scribus.defineColor(cname, c, m, y, k )
+ if spotDict.has_key(cname):
+ scribus.setSpotColor(cname, spotDict[cname])
+
+ #get the pageTitle form user and store it in PageTitle
+ global pageTitle
+ pageTitle=scribus.valueDialog("ColorChart by Sebastian Stetter", "Please enter document title", "Scribus COLOR CHART")
+ drawHeaderFooter(pageTitle)
+
+def createPage():
+ """appends a new page"""
+ scribus.newPage(-1) #append new page
+ #new page - new header and footer
+ drawHeaderFooter(pageTitle)
+
+
+def rgbhex(r,g,b):
+ '''convert rgb values in 0-255 style to hex string in #000000 to #ffffff style'''
+ hr=hex(r)
+ hr = hr.replace("0x", "")
+ if len(hr)== 0:
+ hr = "00"
+ elif len(hr)==1:
+ hr = "0"+hr
+ else:
+ pass
+ hg=hex(g)
+ hg = hg.replace("0x", "")
+ if len(hg)== 0:
+ hg = "00"
+ elif len(hg)==1:
+ hg = "0"+hg
+ else:
+ pass
+ hb=hex(b)
+ hb = hb.replace("0x", "")
+ if len(hb)== 0:
+ hb = "00"
+ elif len(hb)==1:
+ hb = "0"+hb
+ else:
+ pass
+ rgbstring="#"+hr+hg+hb
+ rgbstring=rgbstring.upper()
+ return rgbstring
+
+
+def drawColor(colorname, h, v, width, height): #h horizontal position, v vertical position
+ """draws a color chart field with its caption for the given colorname at the h and v position
+ """
+ #get cmyk values and convert them to 0 - 255 values
+ color = scribus.getColor(colorname)
+ c= int(round(color[0]/2.55))
+ m=int(round(color[1]/2.55))
+ y=int(round(color[2]/2.55))
+ k=int(round(color[3]/2.55))
+ #get rgb color
+ rgbcolor=scribus.getColorAsRGB(colorname)
+ r=rgbcolor[0]
+ g=rgbcolor[1]
+ b=rgbcolor[2]
+ #get webcolor
+ webcolor=rgbhex(r, g, b)
+ #but String for Textbox together
+ colorDisplay = colorname
+ if scribus.isSpotColor(colorname):
+ colorDisplay += " (Spot Color)"
+ colorstring="%s\nC %i, M %i, Y %i, K %i, \nR %i, G %i, B %i \nRGB: %s" %(colorDisplay, c, m, y, k, r, g, b, webcolor)
+
+ #draw rectangle and set colors
+ rect=scribus.createRect(h, v, width, height)
+ scribus.setFillColor(colorname, rect)
+ #if total amount of color is < 20 draw outline in Black for rectangle, else in same color
+ if c +m+y+k < 20:
+ scribus.setLineColor("Black", rect)
+ else:
+ scribus.setLineColor(colorname, rect)
+ #create textbox and insert text
+ textbox=scribus.createText(h+width+5, v, 50, height)
+ #set proper font size
+ scribus.setFontSize(11, textbox)
+ scribus.setTextAlignment(scribus.ALIGN_LEFT, textbox)
+ #load the string into the textbox
+ scribus.insertText(colorstring, 0, textbox)
+
+
+def createChart():
+ """actually handles the whole chart creation process"""
+ prepareDocument()
+ # get page size
+ pageSize=scribus.getPageSize()
+ pageWidth=pageSize[0]
+ pageHeight=pageSize[1]
+ #pageMargins
+ pageMargins=scribus.getPageMargins()
+ topMargin=pageMargins[0]
+ leftMargin=pageMargins[1]
+ rightMargin=pageMargins[2]
+ bottomMargin=pageMargins[3]
+
+ #color field dimensions
+ colorFieldWidth= pageWidth - leftMargin - rightMargin - (TEXT_BOX_WIDTH+HSPACE) #50+5 is the with of the textbox plus the space between textbox and colorfield
+
+ #how much space does one field use?
+ vSpaceUsedByField = COLOR_FIELD_HEIGHT+VSPACE
+
+ #how much space is available per row?
+ vSpaceAvailable=pageHeight-topMargin-bottomMargin-HEADERSIZE-FOOTERSIZE
+
+ #counts the colorFields created for a page. reset this variable after creation of new page
+ colorFieldCounter=0
+
+ #get list of all colors in document
+ colorList = scribus.getColorNames()
+ #prepare the progressbar
+ colorNumber=len(colorList)
+ scribus.progressTotal(colorNumber)
+ #@TODO: implement possibility to abort script (button2=scribus.BUTTON_CANCEL) buttons should return int 1 or 2
+ #scribus.messageBox("ColorChart Script by Sebastian Stetter", "...going to create a chart of "+str(colorNumber)+" colors.\n This may take a while.", button1 = scribus.BUTTON_OK)
+ scribus.statusMessage("Drawing color fields...")
+ stepCompleted=0
+ #disable redrawing for better performance
+ scribus.setRedraw(False)
+ for color in colorList:
+ if (vSpaceUsedByField * (colorFieldCounter+1)) <= vSpaceAvailable:
+ # when there is enought space left draw a color field...
+
+ #calculate Position for new colorField
+ h=leftMargin
+ v=topMargin + (vSpaceUsedByField * colorFieldCounter)+HEADERSIZE
+ #draw the colorField
+ drawColor(color, h, v, colorFieldWidth, COLOR_FIELD_HEIGHT)
+ colorFieldCounter = colorFieldCounter+1
+ #update progressbar
+ stepCompleted = stepCompleted+1
+ scribus.progressSet(stepCompleted)
+ else:
+ #not enough space? create a new page!
+ createPage()
+ #reset the colorFieldCounter to '0' since we created a new page
+ colorFieldCounter = 0
+ h=leftMargin
+ v=topMargin + (vSpaceUsedByField * colorFieldCounter)+HEADERSIZE
+ drawColor(color, h, v, colorFieldWidth, COLOR_FIELD_HEIGHT)
+ colorFieldCounter = colorFieldCounter+1
+
+ #update progressbar
+ stepCompleted = stepCompleted+1
+ scribus.progressSet(stepCompleted)
+
+ #make shure pages are redrawn
+ scribus.setRedraw(True)
+
+
+def main(argv):
+ """just invokes createChart() and displays a message after the chart is finished."""
+ createChart()
+ scribus.messageBox("ColorChart Script by Sebastian Stetter", "Your chart has been created, but not saved, yet!\nThanks for using ColorChart and Scribus!")
+
+
+def main_wrapper(argv):
+ """The main_wrapper() function disables redrawing, sets a sensible generic
+ status bar message, and optionally sets up the progress bar. It then runs
+ the main() function. Once everything finishes it cleans up after the main()
+ function, making sure everything is sane before the script terminates."""
+ try:
+ scribus.statusMessage("Creating color chart...")
+ scribus.progressReset()
+ main(argv)
+ finally:
+ # Exit neatly even if the script terminated with an exception,
+ # so we leave the progress bar and status bar blank and make sure
+ # drawing is enabled.
+ if scribus.haveDoc():
+ scribus.setRedraw(True)
+ scribus.statusMessage("")
+ scribus.progressReset()
+
+# This code detects if the script is being run as a script, or imported as a module.
+# It only runs main() if being run as a script. This permits you to import your script
+# and control it manually for debugging.
+if __name__ == '__main__':
+ main_wrapper(sys.argv)
diff --git a/scribus/plugins/scriptplugin/scripts/DirectImageImport.py b/scribus/plugins/scriptplugin/scripts/DirectImageImport.py
new file mode 100644
index 0000000..369a7ad
--- /dev/null
+++ b/scribus/plugins/scriptplugin/scripts/DirectImageImport.py
@@ -0,0 +1,94 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+
+Diese Skript importiert ein Bild und setzt es auf die akutelle Seite.
+Der Bildrahmen wird dem Bild angepasst und in den nicht-proportionalen Modus
+gesetzt, das heisst, beliebige Verzerrungen sind moeglich.
+
+Um das Bild proportional zu vergroessern, die STRG-Taste beim Bearbeiten druecken.
+
+Tested with scribus 1.3.3.3
+
+Author: Konrad Stania
+
+some modifications 2009 by Gregory Pittman, tested on Scribus 1.3.3.13svn
+
+This newer version uses the Python Imaging Library to get the dimensions of the
+image to be imported, and adjusts the frame accordingly. Initially the frame will
+be created centered, at 80% of the page's width or height, whichever is smaller.
+There is an adjustment to 80% of the height of the page in case this is exceeded
+by the initial calculation.
+
+USAGE:
+
+You must have a document open. Run the script, a dialog asks you to choose an
+image to load. A proportional frame is automatically created and image loaded,
+then adjusted to frame size.
+
+LICENSE:
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+name
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+"""
+
+# Craig Bradney, Scribus Team
+# 10/3/08: Added to Scribus 1.3.3.12svn distribution "as was" from Scribus wiki for bug #6826, script is GPLd
+
+import sys
+
+
+try:
+ from scribus import *
+
+except ImportError:
+ print "This script only runs from within Scribus."
+ sys.exit(1)
+try:
+ from PIL import Image
+except ImportError:
+ print "Unable to import the Python Imaging Library module."
+ sys.exit(1)
+
+def main():
+
+ pageX,pageY = getPageSize()
+ ImageFileName = fileDialog("Image Import", "*","" ,True, False)
+ im = Image.open(ImageFileName)
+ xsize, ysize = im.size
+
+ if (pageX < pageY):
+ Breite = pageX * 0.8
+ else:
+ Breite = pageY * 0.8
+ Hoehe = Breite * ysize/xsize
+
+# for images taller than they are wide we want to limit height of frame to 80% of page height
+ if (Hoehe > pageY * 0.8):
+ Hoehe = pageY * 0.8
+ Breite = Hoehe * xsize/ysize
+
+ ImageFrame = createImage(pageX/2 - Breite/2, pageY/2 - Hoehe/2, Breite, Hoehe)
+ loadImage(ImageFileName, ImageFrame)
+ setScaleImageToFrame(True, False,ImageFrame)
+ setFillColor("None", ImageFrame)
+ setLineColor("None", ImageFrame)
+
+
+if __name__ == '__main__':
+ if haveDoc():
+ main()
+ else:
+ messageBox("Image Import", "You need to have a document open <i>before</i> you can run this script succesfully.", ICON_INFORMATION) \ No newline at end of file
diff --git a/scribus/plugins/scriptplugin/scripts/FontSample.py b/scribus/plugins/scriptplugin/scripts/FontSample.py
new file mode 100644
index 0000000..62bdcfc
--- /dev/null
+++ b/scribus/plugins/scriptplugin/scripts/FontSample.py
@@ -0,0 +1,1578 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# ****************************************************************************
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# ****************************************************************************
+
+"""
+******************************************************************************
+
+DESCRIPTION & USAGE:
+This script needs Tkinter. It will create a GUI with an alphabetical list
+of fonts using the names as they will be shown in Scribus. User can select
+one or more fonts and create an example sheet(s) to print or create a PDF
+from. It is heavily commented to make it easier for the user to adjust it
+for his / her own needs.
+
+Note: this version needs read/write access to .scribus directory in users
+home. You will also need Python Imaging Library (PIL) installed.
+If your system does not meet these requirements then change showPreviewPanel
+to a value of 0. This will disable the new preview features.
+
+******************************************************************************
+
+First release : 30/12/2003
+This release : v0.8.1tk (released 4th Dec 2005)
+Copyright : (C) 2003 - 2005 Steve Callcott
+Latest releases
+and support : www.firstwish.co.uk/sjc/scribus/index.php
+Maintainer : Steve Callcott 2003 - 2005
+Email : stotte@firstwish.co.uk
+
+For revision history see the ChangeLog file.
+Bugs and future plans are listed in the TODO file.
+See NEWS for new features since last version.
+
+WHATS NEW v0.8.2tk:
+A one liner change by Jean Ghali to line #734 to add the extra parameter missing.
+See: http://bugs.scribus.net/view.php?id=4377
+
+WHATS NEW v0.8.1tk:
+After reloading users saved preferences the status bar was not showing
+correct calculations.
+Changed text in settings menu.
+
+WHATS NEW v0.8tk Final:
+Cleaned up the checkbox labels and layout.
+
+WHATS NEW v0.8tk Preview 3:
+Calls the new Scribus zoomDocument() function to make the completed font
+sample document fit in Scribus window.
+
+Grey out "Start page number count from first page" when "Print TOC" is
+not checked as without a table of contents the first page would always
+start on the same page number making this option irrelevant.
+
+WHATS NEW v0.8tk Preview 2:
+Replaced the newDoc() with newDocument(). Have not put any fallback code
+for use with earlier Scribus versions.
+
+When using double sided option we now make use of Scribus ability to display
+pages side by side as default. You may need to zoom out to view the
+complete document width.
+
+WHATS NEW v0.8tk Preview 1:
+Rearanged the initialisation. If no fonts are found for the Table of
+Contents, page numbers and font sample labels, the script shows a
+message box listing the problem and a possible solution as well as a message
+to the console.
+
+A Scribus messagebox alerts the user if Tkinter is not found. Previously
+this message was only printed to the console.
+
+Now able to do a dummy run to calculate and report the amount of samples
+that will fit on a page. This enables the script to correctly calculate
+how many sheets will be required. Previously it was always assumed that
+there would be 3 sample blocks on a sheet. This is now not always the case.
+
+Added menu. Also added "about" and "settings" dialogs.
+
+Sample rows can be selected or unselected to save on paper. The settings are
+automatically saved when changed and can be set as user defaults.
+
+User can choose to have page numbers count from first page of the toc instead
+of the first page of samples. This can be helpful if wanting to quickly look
+up a font in the toc and then using the Scribus page navigator dialog to go to
+the actual page on the screen to view it without printing it out.
+
+Added initial support for a sample paragraph. The sample paragraph defaults
+to "off" due to the amount of space it uses on the page.
+
+Some widgets read their defaults from a config dictionary.
+
+Many code cleanups. Classes used for settings storage have been replaced with
+dictionaries to make it easier for users to customise.
+
+******************************************************************************
+"""
+
+import sys
+import os
+import cPickle
+
+
+showPreviewPanel = 1 # change to 0 to permanently hide the preview
+TEMP_PATH = os.path.join(os.path.expanduser('~'), '.scribus')
+CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.scribus/fontsampler')
+
+
+try:
+ import scribus
+except ImportError,err:
+ print 'This Python script is written for the Scribus scripting interface.'
+ print 'It can only be run from within Scribus.'
+ sys.exit(1)
+
+
+try:
+ from Tkinter import *
+except ImportError,err:
+ print 'This script will not work without Tkinter'
+ scribus.messageBox('Error','This script will not work without Tkinter\nPlease install and try again',
+ scribus.ICON_WARNING)
+ sys.exit(1)
+
+
+if not os.path.exists(CONFIG_PATH):
+ try:
+ print 'Attempting to creating configuration file directory...'
+ os.mkdir(CONFIG_PATH)
+ print 'Success, now testing for write access of new directory...'
+ if os.access(CONFIG_PATH, os.W_OK):
+ print 'Write access ok.'
+ else:
+ print 'Error, unable to write to .scribus/fontsampler directory.'
+ except:
+ CONFIG_PATH = ''
+ print 'Failed to make configuration file directory,'
+ print 'do you have a .scribus directory in your home directory?'
+ print 'font sampler will not be able to save your preferences'
+
+
+try:
+ import Image
+except ImportError,err:
+ print 'You need to install Python Imaging Library (PIL).'
+ print 'If using gentoo then you need to emerge /dev-python/imaging'
+ print 'If using an RPM based linux distribution then you add python-imaging or similar.'
+ print 'Script will continue without the font preview panel.'
+ showPreviewPanel = 0
+
+
+try:
+ import ImageTk
+except ImportError,err:
+ print 'Module ImageTk not found, font preview disabled'
+ showPreviewPanel = 0
+
+
+if showPreviewPanel:
+ if not os.path.exists(TEMP_PATH):
+ print '.scribus folder not found, disabling font preview panel'
+ showPreviewPanel = 0
+ if not os.access(TEMP_PATH, os.W_OK):
+ print 'Unable to write to .scribus folder, disabling font preview panel'
+ showPreviewPanel = 0
+
+
+# A few globals for use later...
+gSamplePic = None
+gPreviewId = None
+
+#*************************************************************************
+
+WINDOW_TITLE = 'Font Sampler v0.8.1tk - Steve Callcott'
+SUPPORT_PAGE = 'www.firstwish.co.uk/sjc/scribus/index.php'
+
+fontsListFixed = (
+ 'Luxi Mono Regular',
+ 'Nimbus Mono L Regular',
+ 'Courier 10 Pitch Regular',
+ 'Courier New Regular',
+ 'Courier Regular',
+ 'Andale Mono Regular',
+ 'Larabiefont Regular'
+)
+
+fontsListProportional = (
+ 'Nimbus Sans L Regular',
+ 'Luxi Sans Regular',
+ 'Bitstream Vera Sans',
+ 'Helvetica',
+ 'Arial Regular'
+)
+
+defaultPrefs = {
+ 'wantDoubleSided': 0,
+ 'paperSize':'A4', # currently PAPER_LETTER or PAPER_A4
+ 'wantTOC': 1,
+ 'wantBindingOffset': 0,
+ 'wantPageNumbers': 1,
+ 'wantPageOneOnFirst': 0,
+ 'wantAlphabet' : 1,
+ 'want6Point' : 1,
+ 'want8Point' : 1,
+ 'want10Point' : 1,
+ 'want12Point' : 1,
+ 'want16Point' : 1,
+ 'want20Point' : 1,
+ 'want32Point' : 1,
+ 'wantParagraph' : 0 # Uses a lot of space so default is off
+}
+
+userPrefs = {}
+
+geometriesList = [
+ {
+ 'paperName' : 'A4',
+ 'paperSize' : scribus.PAPER_A4,
+ 'paperWidth' : 595,
+ 'paperHeight' : 842,
+ 'paperTopMargin' : 60,
+ 'paperBottomMargin' : 50,
+ 'paperLeftMargin' : 50,
+ 'paperRightMargin' : 50,
+ 'paperBinding' : 16,
+ 'tocRowsPerPage' : 57,
+ 'paperPageNumVertOffset' : 16
+ },
+ {
+ 'paperName' : 'US Letter',
+ 'paperSize' : scribus.PAPER_LETTER,
+ 'paperWidth' : 612,
+ 'paperHeight' : 792,
+ 'paperTopMargin' : 27,
+ 'paperBottomMargin' : 45,
+ 'paperLeftMargin' : 50,
+ 'paperRightMargin' : 50,
+ 'paperBinding' : 18,
+ 'tocRowsPerPage' : 56,
+ 'paperPageNumVertOffset' : 16
+ }
+]
+
+# define our data dictionary and some of the data...
+dD = {
+ 'tocHeaderTitle' : 'Table of Contents',
+ 'tocCharsInRow' : 75,
+ 'previewpanelFontHeight' : 28,
+ 'previewpanelSampleText' : 'Woven silk pyjamas exchanged for blue quartz'
+}
+
+samplesHeader = {
+ 'fontSize' : 16,
+ 'lineSpace' : 15,
+ 'textHeight' : 23
+}
+
+# Use \xBC etc to insert Hex ascii chars into the sample strings below.
+sampleAlphabet = {
+ 'fontSize' : 10.5,
+ 'lineSpace' : 12,
+ 'textString' : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#?$*&',
+ 'textHeight' : 18
+}
+
+sample6Point = {
+ 'fontSize' : 6,
+ 'lineSpace' : 6,
+ 'textString' : 'This line is in 6 point',
+ 'textHeight' : 13
+}
+
+sample8Point = {
+ 'fontSize' : 8,
+ 'lineSpace' : 8,
+ 'textString' : 'This line is in 8 point',
+ 'textHeight' : 16
+}
+
+sample10Point = {
+ 'fontSize' : 10,
+ 'lineSpace' : 11,
+ 'textString' : 'This line is in 10 point',
+ 'textHeight' : 19
+}
+
+sample12Point = {
+ 'fontSize' : 12,
+ 'lineSpace' : 11,
+ 'textString' : 'This line is in 12 point',
+ 'textHeight' : 21
+}
+
+sample16Point = {
+ 'fontSize' : 16,
+ 'lineSpace' : 13,
+ 'textString' : 'This line is in 16 point',
+ 'textHeight' : 26
+}
+
+sample20Point = {
+ 'fontSize' : 20,
+ 'lineSpace' : 16,
+ 'textString' : 'This line is in 20 point',
+ 'textHeight' : 31
+}
+
+sample32Point = {
+ 'fontSize' : 32,
+ 'lineSpace' : 29,
+ 'textString' : 'This line is in 32 point',
+ 'textHeight' : 49
+}
+
+sampleParagraph = {
+ 'fontSize' : 9,
+ 'lineSpace' : 10.8,
+ 'textHeight' : 175
+}
+
+sampleParagraphText = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut a sapien. \
+Aliquam aliquet purus molestie dolor. Integer quis eros ut erat posuere dictum. \
+Curabitur dignissim. Integer orci. Fusce vulputate lacus at ipsum. Quisque in libero \
+nec mi laoreet volutpat. Aliquam eros pede, scelerisque quis, tristique cursus, \
+placerat convallis, velit. Nam condimentum. Nulla ut mauris. Curabitur adipiscing, \
+mauris non dictum aliquam, arcu risus dapibus diam, nec sollicitudin quam erat quis \
+ligula. Aenean massa nulla, volutpat eu, accumsan et, fringilla eget, odio. \
+Nulla placerat porta justo. Nulla vitae turpis.\n\nPraesent lacus.Lorem ipsum dolor sit \
+amet, consectetuer adipiscing elit. Pellentesque habitant morbi tristique senectus \
+et netus et malesuada fames ac turpis egestas. Quisque vel erat eget diam \
+consectetuer iaculis. Cras ante velit, suscipit et, porta tempus, dignissim quis, \
+magna. Vivamus viverra, turpis nec rhoncus ultricies, diam turpis eleifend nisl, a \
+eleifend ante felis ac sapien. Integer bibendum. Suspendisse in mi non neque \
+bibendum convallis. Suspendisse potenti. Sed sit amet purus at felis adipiscing \
+aliquam. Vivamus et nisl sit amet mauris aliquet molestie. Integer tortor massa, \
+aliquam a, lacinia nonummy, sagittis nec, eros.'
+
+#*************************************************************************
+
+def set_font_fixed(fontList):
+ """Find a matching font for the Table of Contents."""
+ availableFonts = scribus.getFontNames()
+ found = 0
+ for f in fontList:
+ if found:
+ break
+ for i in availableFonts:
+ if not found:
+ if f == i:
+ return f
+ found = 1
+ break
+ if not found:
+ errorList = ''
+ for j in fontList:
+ errorList = errorList + j + '\n'
+ errorMessage ='No suitable fixed width font found.\nPlease install at least one of these fixed width fonts:\n'+errorList
+ print errorMessage
+ raise Exception(errorMessage)
+
+
+def set_font_proportional(fontList):
+ """Find a matching font for the page numbers and font names above samples."""
+ availableFonts = scribus.getFontNames()
+ found = 0
+ for p in fontList:
+ if found:
+ break
+ for i in availableFonts:
+ if not found:
+ if p == i:
+ return p
+ found = 1
+ break
+ if not found:
+ errorList = ''
+ for j in fontList:
+ errorList = errorList + j + '\n'
+ errorMessage = 'No suitable proportional font found.\nPlease install at least one of these proportional fonts:\n'+errorList
+ print errorMessage
+ raise Exception(errorMessage)
+
+
+def save_user_conf(path):
+ """Save the data to the save file on the path specified by CONFIG_PATH.
+
+ Note initialisation unsets the CONFIG_PATH if it failed to verify or create"""
+ if not path == '':
+ try:
+ file = open(os.path.join(path,'fontsampler.conf'), 'w')
+ data = {
+ 'a' : defaultPrefs,
+ 'b' : userPrefs
+ }
+ cPickle.dump(data, file)
+ file.close()
+ except:
+ print 'failed to save data'
+
+
+def restore_user_conf(path):
+ """Restore the data from the save file on the path specified by CONFIG_PATH."""
+ try:
+ file = open(os.path.join(path,'fontsampler.conf'), 'r')
+ data = cPickle.load(file)
+ file.close()
+ defaultPrefs.update(data['a'])
+ userPrefs.update(data['b'])
+ except:
+ userPrefs.update(defaultPrefs)
+ print 'failed to load saved data so using default values defined in the script'
+
+
+def set_page_geometry(dD, geometriesList, paperSize, wantBindingOffset):
+ """This is the experimental replacement paper size setting function.
+
+ Each paper size and other associated data are stored in a dictionary.
+ The dictionaries are stored in a list. We copy appropriate dictionary
+ and custom calculations into a work dictionary for use.
+ The advantage of this is its easier to add new paper definitions.
+ Returns a new dictionary, use .update to merge in new values into dD.
+ """
+ try:
+ result={}
+ for i in geometriesList:
+ if i['paperName'] == paperSize:
+ dD.update(i)
+
+ result['paperLeftMarginOdd'] = dD['paperLeftMargin'] + \
+ dD['paperBinding']
+ result['paperRightMarginEven'] = dD['paperRightMargin'] + \
+ dD['paperBinding']
+ result['paperTextHeight'] = dD['paperHeight'] - \
+ dD['paperTopMargin'] - \
+ dD['paperBottomMargin']
+ result['paperMargins'] = dD['paperLeftMargin'],dD['paperRightMargin'],dD['paperTopMargin'],dD['paperBottomMargin']
+
+ # if we are adding a binding offset to the margins then we will have less width for our text...
+ if wantBindingOffset:
+ result['paperTextWidth'] = dD['paperWidth'] - \
+ dD['paperLeftMargin'] - \
+ dD['paperRightMargin'] - \
+ dD['paperBinding'] - \
+ 2
+ else:
+ result['paperTextWidth'] = dD['paperWidth'] - \
+ dD['paperLeftMargin'] - \
+ dD['paperRightMargin'] - \
+ 2
+ return result
+ except:
+ errorMessage = 'set_page_geometry() failure: %s' % sys.exc_info()[1]
+ print errorMessage
+
+
+def set_odd_even(pageNum):
+ """ Sets the left margin position.
+
+ Checks the number passed to it and sets left margin accordingly.
+ Call once after each new page is created.
+ Returns 1 if even and 0 if odd page.
+ """
+ if pageNum % 2 == 0:
+ isEvenPage = 1 # Even side
+ else:
+ isEvenPage = 0 # Odd side
+
+ if userPrefs['wantBindingOffset']:
+ if isEvenPage and userPrefs['wantDoubleSided']: # Even (when double sided)
+ dD['paperLeftSide'] = dD['paperLeftMargin'] + 1
+ else: # Odd side
+ dD['paperLeftSide'] = dD['paperLeftMarginOdd'] + 1
+ else: # No binding
+ dD['paperLeftSide'] = dD['paperLeftMargin'] + 1
+ return isEvenPage
+
+
+def draw_sample_row(font, fontSize, lineSpace, textString, x, y, w, h, getSizeOnly):
+ """Creates one row of samples or a header for the top of the block.
+
+ Called once by draw_sample_block() to create a block label then as many times
+ as required to create each actual sample found in the list of dictionaries
+ containing each samples definition.
+ """
+ if not getSizeOnly:
+ f = scribus.createText(x, y, w, h)
+ scribus.insertText(textString, 0, f)
+ scribus.setFont(font, f)
+ scribus.setFontSize(fontSize, f)
+ scribus.setLineSpacing(lineSpace, f)
+ scribus.setTextAlignment(0, f)
+ return y + h + 1
+
+
+def draw_sample_block(fontName, x, y, w, getSizeOnly):
+ """Drawing of a complete sample block starts from here.
+
+ Iterates through each sample declared in the "samples" tuple. Places one
+ complete block using the font specified in fontname.
+ Note top line on page is drawn outside of this function. This ensures ease
+ of returning same height of every sample block. Line could have been drawn
+ at top inside this function and page finalised with line at bottom instead.
+ If getSizeOnly is true then returns the overall height of the entire text
+ block but without actually placing it.
+ """
+ startPos = y
+ # Note there are 2 points of space before horizontal line at bottom of block.
+ # This 2 points will not appear at top of page so need to add it.
+
+ # set space below horizontal line to the top of the text block
+ y = y + 4
+
+ # (note there is one extra point inserted by addSampleRow() for each row generated)...
+
+ # first need a header...
+ y = draw_sample_row(dD['bookstylePropFont'], samplesHeader['fontSize'], samplesHeader['lineSpace'], fontName, x, y, w, samplesHeader['textHeight'], getSizeOnly)
+
+ if userPrefs['wantAlphabet']:
+ y = draw_sample_row(fontName, sampleAlphabet['fontSize'], sampleAlphabet['lineSpace'], sampleAlphabet['textString'], x, y, w, sampleAlphabet['textHeight'], getSizeOnly)
+
+ if userPrefs['want6Point']:
+ y = draw_sample_row(fontName, sample6Point['fontSize'], sample6Point['lineSpace'], sample6Point['textString'], x, y, w, sample6Point['textHeight'], getSizeOnly)
+
+ if userPrefs['want8Point']:
+ y = draw_sample_row(fontName, sample8Point['fontSize'], sample8Point['lineSpace'], sample8Point['textString'], x, y, w, sample8Point['textHeight'], getSizeOnly)
+
+ if userPrefs['want10Point']:
+ y = draw_sample_row(fontName, sample10Point['fontSize'], sample10Point['lineSpace'], sample10Point['textString'], x, y, w, sample10Point['textHeight'], getSizeOnly)
+
+ if userPrefs['want12Point']:
+ y = draw_sample_row(fontName, sample12Point['fontSize'], sample12Point['lineSpace'], sample12Point['textString'], x, y, w, sample12Point['textHeight'], getSizeOnly)
+
+ if userPrefs['want16Point']:
+ y = draw_sample_row(fontName, sample16Point['fontSize'], sample16Point['lineSpace'], sample16Point['textString'], x, y, w, sample16Point['textHeight'], getSizeOnly)
+
+ if userPrefs['want20Point']:
+ y = draw_sample_row(fontName, sample20Point['fontSize'], sample20Point['lineSpace'], sample20Point['textString'], x, y, w, sample20Point['textHeight'], getSizeOnly)
+
+ if userPrefs['want32Point']:
+ y = draw_sample_row(fontName, sample32Point['fontSize'], sample32Point['lineSpace'], sample32Point['textString'], x, y, w, sample32Point['textHeight'], getSizeOnly)
+
+ if userPrefs['wantParagraph']:
+ y = draw_sample_row(fontName, sampleParagraph['fontSize'], sampleParagraph['lineSpace'], sampleParagraphText, x, y, w, sampleParagraph['textHeight'], getSizeOnly)
+
+ y = y + 1 # one extra point of space above bottom Horiz. line
+
+ lineHeight = draw_horiz_line(y, x, w + x, getSizeOnly)
+ y = y + lineHeight
+
+ return y - startPos
+
+
+def insert_toc_row(fontName, pageNum, yPos, frame):
+ """Called once for each content line to be drawn in the text frame."""
+ dotLine = ""
+ dotQuant = dD['tocCharsInRow'] - len(fontName) - len(str(pageNum)) + 1
+ for i in range(dotQuant):
+ dotLine = dotLine + '.'
+ oneLine = fontName + dotLine + str(pageNum) + "\n"
+ scribus.insertText(oneLine, yPos, frame)
+ yPos = yPos + len(oneLine) + 0
+ return yPos
+
+
+def build_toc_page_template():
+ """Inserts empty toc template into the currently selected page."""
+ # first put a header on the empty page...
+ textstring = dD['tocHeaderTitle']
+ yPos = dD['paperTopMargin'] + 1
+ header = scribus.createText(dD['paperLeftSide'], yPos, dD['paperTextWidth'], 35)
+ scribus.insertText(textstring, 0, header)
+ scribus.setFont(dD['bookstylePropFont'], header)
+ scribus.setFontSize(24, header)
+ scribus.setTextAlignment(1, header)
+ # now create a text frame for the table of contents...
+ yPos = yPos + 36
+ body = scribus.createText(dD['paperLeftSide'], yPos, dD['paperTextWidth'], dD['paperHeight'] - yPos - dD['paperBottomMargin'] - 1)
+ scribus.setFont(dD['bookstyleFixedFont'], body)
+ scribus.setFontSize(10, body)
+ scribus.setLineSpacing(12, body)
+ return body
+
+
+def build_toc(tocList):
+ """Creates all the Table of Contents pages.
+
+ Calls tocPageFramesBuild() to write the header and empty frame for the
+ toc rows each time a new page is added.
+ Then calls tocRowAdd() to add each line to the toc frame. Creates new page
+ each time it completes last row on page.
+ """
+ rowCount = 0
+ yPos = 0
+ tocPageNum = 1
+ tocPageCount = 1
+
+ scribus.newPage(tocPageNum)
+ isEvenPage = set_odd_even(tocPageNum)
+ body = build_toc_page_template() # create frames for new empty page
+ if isEvenPage == 0:
+ scribus.setTextAlignment(2, body)
+ else:
+ scribus.setTextAlignment(0, body)
+ for i in tocList:
+ if rowCount == dD['tocRowsPerPage']: # Need to build a new TOC page (count is from zero, not one)
+ tocPageNum = tocPageNum + 1
+ scribus.newPage(tocPageNum)
+ isEvenPage = set_odd_even(tocPageNum)
+ body = build_toc_page_template()
+ if not isEvenPage:
+ scribus.setTextAlignment(2, body)
+ else:
+ scribus.setTextAlignment(0, body)
+ rowCount = 0
+ yPos = 0
+ tocPageCount = tocPageCount + 1
+ yPos = insert_toc_row(i[0], i[1], yPos, body)
+ rowCount = rowCount + 1
+ if userPrefs['wantDoubleSided']:
+ if tocPageCount % 2 != 0: # Odd page
+ tocPageNum = tocPageNum + 1
+ scribus.newPage(tocPageNum) # Add an extra page if odd number
+
+
+def add_page_num(pageNum):
+ yPos = dD['paperHeight'] - \
+ dD['paperBottomMargin'] - \
+ dD['paperPageNumVertOffset']
+ footer = scribus.createText(dD['paperLeftSide'], yPos, dD['paperTextWidth'], 15)
+ scribus.insertText('%s' % pageNum, 0, footer)
+ scribus.setFont(dD['bookstylePropFont'], footer)
+ scribus.setFontSize(9, footer)
+ scribus.setTextAlignment(1, footer)
+ scribus.setLineSpacing(10, footer)
+
+
+def create_empty_samplepage(pageNum, getSizeOnly):
+ """Creates a new page and increments page number by one.
+
+ Note getSizeOnly is now evaluated. Will still generate page number increment
+ but will not actually create the new page or place the number on the page."""
+ if not getSizeOnly:
+ scribus.newPage(-1)
+ pageNum = pageNum + 1
+ set_odd_even(pageNum)
+ if not getSizeOnly:
+ if userPrefs['wantPageNumbers']:
+ add_page_num(pageNum)
+ return pageNum
+
+
+def draw_horiz_line(yPos, xStart, xEnd, getSizeOnly):
+ """Draws a line and returns the height.
+
+ If getSizeOnly is set then returns the height it would have
+ used but without actually creating a line.
+ """
+ lineWidth = 1
+ if not getSizeOnly:
+ newLine = scribus.createLine(xStart, yPos, xEnd, yPos)
+ scribus.setLineWidth(lineWidth, newLine)
+ return lineWidth
+
+
+def draw_selection(fontList, getSizeOnly):
+ """Draws the sample blocks onto the Scribus canvas.
+
+ Measure one font sample block including any horizontal lines and extra
+ vertical spaces.
+ Get the amount of vertical space available for the text area between the
+ top line and top of page number area.
+ Use these two values to calculate how many complete sample blocks will fit
+ in the space available. This is the "pageBlocks"
+ Note we always draw the top horizontal line before placing the blocks. This
+ is taken into account when calculating the available text area.
+ Next, if "getSizeOnly" is false we create a page then create the sample
+ blocks while incrementing a counter until it matches the "pageBlocks".
+ Reset the counter and create new page. We keep going until we have processed
+ all the fonts in the selection list.
+ We update the Scribus progress bar as we create each font sample block.
+ The returned result is used to update some values in the status bar.
+ """
+ progress = 1
+ scribus.progressReset()
+ scribus.progressTotal(len(fontList))
+ tocList = []
+ pageNum = 1
+ blockCounter = 0
+ counter = 0
+ facingPages = scribus.NOFACINGPAGES
+
+ # Just get blocks per page value...
+ set_odd_even(pageNum)
+ lineHeight = 1 # include the one point of space below top margin
+ lineHeight = lineHeight + draw_horiz_line(0, dD['paperLeftSide'], dD['paperLeftSide'] + dD['paperTextWidth'], 1)
+ usuableArea = dD['paperHeight'] - \
+ dD['paperTopMargin'] - \
+ lineHeight - \
+ dD['paperBottomMargin'] - \
+ dD['paperPageNumVertOffset']
+
+ blockHeight = draw_sample_block(fontList[0], dD['paperLeftSide'], 0, dD['paperTextWidth'], 1)
+ pageBlocks = int(usuableArea / blockHeight)
+ #print blockHeight
+ #print "Usuable area %s points high" % usuableArea
+ #print "Used space on page is %s points high" % (blockHeight * pageBlocks)
+
+ if not getSizeOnly:
+ # not a dummy run so start by setting up page numbering...
+ if userPrefs['wantPageOneOnFirst'] and userPrefs['wantTOC']:
+ tocPageCount = divmod(len(fontList), dD['tocRowsPerPage'])
+ pageNum = pageNum + tocPageCount[0]
+ if tocPageCount[1] != 0:
+ # (adding more to page number as not whole number)
+ pageNum = pageNum + 1
+ if userPrefs['wantDoubleSided']:
+ oddEvenTest = divmod(pageNum, 2)
+ if oddEvenTest[1] == 0:
+ # (adding extra one to start number as odd amount)
+ pageNum = pageNum + 1
+ if userPrefs['wantDoubleSided']:
+ facingPages = scribus.FACINGPAGES
+ # now create a new document with empty page and start building...
+ scribus.newDocument(dD['paperSize'], dD['paperMargins'], scribus.PORTRAIT, 1, scribus.UNIT_POINTS, facingPages, scribus.FIRSTPAGERIGHT, 1)
+ scribus.zoomDocument(-100)
+ # A new doc gives us a new page by default so set it up first...
+ set_odd_even(pageNum)
+ yPos = dD['paperTopMargin'] + 1
+ lineHeight = draw_horiz_line(yPos, dD['paperLeftSide'], dD['paperLeftSide'] + dD['paperTextWidth'], getSizeOnly)
+ yPos = yPos + lineHeight
+ if userPrefs['wantPageNumbers']:
+ add_page_num(pageNum)
+ for i in fontList:
+ # Now place the actual sample block but create a new page if needed...
+ if counter == pageBlocks:
+ pageNum = create_empty_samplepage(pageNum, getSizeOnly)
+ yPos = dD['paperTopMargin'] + 1
+ lineHeight = draw_horiz_line(yPos, dD['paperLeftSide'], dD['paperLeftSide'] + dD['paperTextWidth'], getSizeOnly)
+ yPos = yPos + lineHeight
+ counter = 0
+ blockHeight = draw_sample_block(i, dD['paperLeftSide'], yPos, dD['paperTextWidth'], getSizeOnly)
+ yPos = yPos + blockHeight
+ # and also increment the Scribus progress bar...
+ scribus.progressSet(progress)
+ progress = progress + 1
+ # Add current font to TOC...
+ tocList.append([i, pageNum])
+ counter = counter + 1
+ if userPrefs['wantTOC']:
+ # Insert table of contents - (before page numbering)...
+ build_toc(tocList)
+ scribus.gotoPage(1)
+ return pageBlocks
+
+
+def preview_font(app, fontName):
+ """Gets the named font and puts a sample in the preview panel.
+
+ Pick up the temp sample qpixmap file and display it in a canvas object
+ The temp file is put in the users ".scribus" folder and cleaned up on exit.
+ We create samplePic as a global as a workaround because the reference count
+ does not increase when we add the image to the canvas. Therefore python
+ garbage collection removes our image before we have even displayed it.
+ Note app.previewPanel is the actual canvas.
+ """
+ global gSamplePic
+ global gPreviewId
+ scribus.renderFont(fontName, os.path.join(TEMP_PATH,'temp079r.bmp'),dD['previewpanelSampleText'],dD['previewpanelFontHeight'])
+ try:
+ tempPic = Image.open(os.path.join(TEMP_PATH,'temp079r.bmp'))
+ tempPic.save(os.path.join(TEMP_PATH,'temp079r.jpeg'),format='JPEG')
+ tempImage = Image.open(os.path.join(TEMP_PATH,'temp079r.jpeg'))
+ imgDimen = tempPic.getbbox()
+ gSamplePic = ImageTk.PhotoImage(tempImage)
+ # To center the image use "Half display height minus half the image height"
+ # preview panel is allegedly 56 (60 less a 2 pixel border top and bottom)
+ # need to be lower than that to look correct visually...
+ topEdge = (32 - (imgDimen[3] / 2))
+ gPreviewId = app.previewPanel.create_image(5, topEdge, anchor=NW, image=gSamplePic)
+ os.remove(os.path.join(TEMP_PATH,'temp079r.bmp'))
+ os.remove(os.path.join(TEMP_PATH,'temp079r.jpeg'))
+ except IOError:
+ gSamplePic = None
+ gPreviewId = app.previewPanel.create_image(0, 0, anchor=NW, image=gSamplePic)
+ return
+
+
+class AboutDialog(Toplevel):
+
+ def __init__(self, parent):
+ Toplevel.__init__(self, parent)
+ self.transient(parent)
+ self.title('About')
+ self.parent = parent
+ self.result = None
+ self.resizable(0, 0)
+
+ infoLabel = Label(self, text=WINDOW_TITLE+'\nSupport page at %s' % SUPPORT_PAGE)
+ infoLabel.pack(padx=5, pady=5)
+ # now the frame for contents...
+ contentFrame = Frame(self)
+ self.btnOk = Button(contentFrame, text='OK', command=self.ok, default=ACTIVE)
+ self.btnOk.pack(side=LEFT, padx=5, pady=5)
+ contentFrame.pack()
+ self.bind('<Return>', self.ok)
+ self.grab_set()
+ self.protocol('WM_DELETE_WINDOW', self.ok)
+ self.initial_focus = self.btnOk
+ self.wait_window(self)
+
+ def ok(self, event=None):
+ self.withdraw()
+ self.update_idletasks()
+ self.parent.focus_set()
+ self.destroy()
+
+
+class ConfigurationDialog(Toplevel):
+
+ def __init__(self, parent):
+ Toplevel.__init__(self, parent)
+ self.transient(parent)
+ self.title('Configuration')
+ self.parent = parent
+ self.result = None
+ self.resizable(0, 0)
+
+ # Create outer frame...
+ self.topFrame = Frame(self, bd=1, relief=FLAT)
+ self.topFrame.grid(row=0, column=0, padx=5, pady=5)
+
+ self.paperSizeLabel = Label(self.topFrame, text='Sample Rows:')
+ self.paperSizeLabel.grid(row=0, column=0, sticky=W)
+
+ # This frame holds each sample selector...
+ self.sampleSelectFrame = Frame(self.topFrame, bd=1, relief=RIDGE)
+ self.sampleSelectFrame.grid(row=1, column=0, padx=0, pady=2)
+
+ # now create the sample selector widgets for the frame...
+ self.__wantAlphabet = IntVar()
+ self.btnWantAlphabet = Checkbutton(self.sampleSelectFrame, text='want alphabet row', variable=self.__wantAlphabet, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
+ self.btnWantAlphabet.grid(row=0, column=0, padx=10, pady=0, sticky=W)
+ if userPrefs['wantAlphabet']:
+ self.btnWantAlphabet.select()
+
+ self.__want6Point = IntVar()
+ self.btnWant6Point = Checkbutton(self.sampleSelectFrame, text='want 6 point row', variable=self.__want6Point, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
+ self.btnWant6Point.grid(row=1, column=0, padx=10, pady=0, sticky=W)
+ if userPrefs['want6Point']:
+ self.btnWant6Point.select()
+
+ self.__want8Point = IntVar()
+ self.btnWant8Point = Checkbutton(self.sampleSelectFrame, text='want 8 point row', variable=self.__want8Point, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
+ self.btnWant8Point.grid(row=2, column=0, padx=10, pady=0, sticky=W)
+ if userPrefs['want8Point']:
+ self.btnWant8Point.select()
+
+ self.__want10Point = IntVar()
+ self.btnWant10Point = Checkbutton(self.sampleSelectFrame, text='want 10 point row', variable=self.__want10Point, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
+ self.btnWant10Point.grid(row=3, column=0, padx=10, pady=0, sticky=W)
+ if userPrefs['want10Point']:
+ self.btnWant10Point.select()
+
+ self.__want12Point = IntVar()
+ self.btnWant12Point = Checkbutton(self.sampleSelectFrame, text='want 12 point row', variable=self.__want12Point, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
+ self.btnWant12Point.grid(row=4, column=0, padx=10, pady=0, sticky=W)
+ if userPrefs['want12Point']:
+ self.btnWant12Point.select()
+
+ self.__want16Point = IntVar()
+ self.btnWant16Point = Checkbutton(self.sampleSelectFrame, text='want 16 point row', variable=self.__want16Point, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
+ self.btnWant16Point.grid(row=5, column=0, padx=10, pady=0, sticky=W)
+ if userPrefs['want16Point']:
+ self.btnWant16Point.select()
+
+ self.__want20Point = IntVar()
+ self.btnWant20Point = Checkbutton(self.sampleSelectFrame, text='want 20 point row', variable=self.__want20Point, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
+ self.btnWant20Point.grid(row=6, column=0, padx=10, pady=0, sticky=W)
+ if userPrefs['want20Point']:
+ self.btnWant20Point.select()
+
+ self.__want32Point = IntVar()
+ self.btnWant32Point = Checkbutton(self.sampleSelectFrame, text='want 32 point row', variable=self.__want32Point, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
+ self.btnWant32Point.grid(row=7, column=0, padx=10, pady=0, sticky=W)
+ if userPrefs['want32Point']:
+ self.btnWant32Point.select()
+
+ self.__wantParagraph = IntVar()
+ self.btnParagraphSelect = Checkbutton(self.sampleSelectFrame, text='want sample paragraph', variable=self.__wantParagraph, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
+ self.btnParagraphSelect.grid(row=8, column=0, padx=10, pady=0, sticky=W)
+ if userPrefs['wantParagraph']:
+ self.btnParagraphSelect.select()
+
+ self.paperSizeLabel = Label(self.topFrame, text='Paper Sizes:')
+ self.paperSizeLabel.grid(row=2, column=0, sticky=W)
+
+ self.paperSizeFrame = Frame(self.topFrame, bd=1, relief=RIDGE)
+ self.paperSizeFrame.grid(row=3, column=0, padx=0, pady=2, sticky=W)
+
+ self.__paper = StringVar()
+ self.a4papersizeSelect = Radiobutton(self.paperSizeFrame, text='A4', variable=self.__paper, value='A4', command=self.__paperSelectionClick)
+ self.a4papersizeSelect.grid(row=1, column=0, padx=10, sticky=W)
+ self.uspapersizeSelect = Radiobutton(self.paperSizeFrame, text='US Letter', variable=self.__paper, value='US Letter', command=self.__paperSelectionClick)
+ self.uspapersizeSelect.grid(row=2, column=0, padx=10, sticky=W)
+
+ # set to match prefs...
+ if userPrefs['paperSize'] == 'US Letter':
+ self.uspapersizeSelect.select()
+ if userPrefs['paperSize'] == 'A4':
+ self.a4papersizeSelect.select()
+
+ self.btnFrame = Frame(self.topFrame)
+ self.btnFrame.grid(row=4, column=0, padx=10, pady=2)
+ self.btnOk = Button(self.btnFrame, text='OK', command=self.ok)
+ self.btnOk.grid(row=2, column=0, pady=5)
+ self.bind('<Return>', self.ok)
+ self.grab_set()
+ self.initial_focus = self.btnOk
+ self.wait_window(self)
+
+
+ def __sampleSelectionClick(self):
+ """Get and store all the selections.
+
+ Just assigns the lot at once. Not worth being picky and only
+ assigning values that have changed since last time.
+ """
+ userPrefs['wantAlphabet'] = self.__wantAlphabet.get()
+ userPrefs['want6Point'] = self.__want6Point.get()
+ userPrefs['want8Point'] = self.__want8Point.get()
+ userPrefs['want10Point'] = self.__want10Point.get()
+ userPrefs['want12Point'] = self.__want12Point.get()
+ userPrefs['want16Point'] = self.__want16Point.get()
+ userPrefs['want20Point'] = self.__want20Point.get()
+ userPrefs['want32Point'] = self.__want32Point.get()
+ userPrefs['wantParagraph'] = self.__wantParagraph.get()
+ self.parent.statusbarUpdate()
+
+ def __paperSelectionClick(self):
+ userPrefs['paperSize'] = self.__paper.get()
+ self.parent.statusbarUpdate()
+
+ def ok(self, event=None):
+ dD.update(set_page_geometry(dD, geometriesList, userPrefs['paperSize'], userPrefs['wantBindingOffset']))
+ self.withdraw()
+ self.update_idletasks()
+ self.parent.focus_set()
+ self.destroy()
+
+
+class Application(Frame):
+
+ def __init__(self, master = None):
+ Frame.__init__(self, master)
+
+ self.grid()
+
+ # Remove maximise button and resize. Not good to allow resizable window
+ # because the listboxes are fixed width...
+ self.master.resizable(0, 0)
+
+ # build the menu...
+ menubar = Menu(self)
+ settingsmenu = Menu(menubar, tearoff=0)
+ settingsmenu.add_command(label='Configuration', command=self.__configurationDlgShow)
+ settingsmenu.add_separator()
+ settingsmenu.add_command(label='Save current settings', command=self.__saveCurrentSettingsAsDefaults)
+ settingsmenu.add_command(label='Load saved settings', command=self.__restoreCurrentSettingsFromDefault)
+
+ menubar.add_cascade(label='Settings', menu=settingsmenu)
+ helpmenu = Menu(menubar, tearoff=0)
+ helpmenu.add_command(label='About', command=self.__aboutDlgShow)
+ menubar.add_cascade(label='Help', menu=helpmenu)
+ # display menu...
+ self.master.config(menu=menubar)
+
+ # now start adding our widgets starting with the top frame...
+ self.listbox_frame = Frame(self)
+ self.listbox_frame.grid(row=0, column=0, sticky=EW)
+
+ # left hand listbox assembly
+ self.leftListbox_frame = Frame(self.listbox_frame, borderwidth=1, relief=SUNKEN)
+ self.leftListbox_frame.grid(row=1, column=0)
+
+ self.leftLabel = Label(self.listbox_frame, text='Available Fonts')
+ self.leftLabel.grid(row=0, column=0, sticky=NS)
+
+ self.yScroll1 = Scrollbar(self.leftListbox_frame, orient=VERTICAL)
+ self.yScroll1.grid(row=0, column=1, sticky=NS)
+ self.xScroll1 = Scrollbar(self.leftListbox_frame, orient=HORIZONTAL)
+ self.xScroll1.grid(row=1, column=0, sticky=EW)
+
+ self.listbox1 = Listbox(self.leftListbox_frame,
+ xscrollcommand=self.xScroll1.set,
+ yscrollcommand=self.yScroll1.set,
+ selectmode=EXTENDED,
+ height=20, width=40)
+ self.listbox1.grid(row=0, column=0, sticky=NSEW)
+ self.xScroll1['command'] = self.listbox1.xview
+ self.yScroll1['command'] = self.listbox1.yview
+
+ def __listbox1KeyRelease(event):
+ """Check if an Up or Down key has been pressed and released and
+ if so the preview panel is refreshed. If the keys are held down
+ the file system slows the scroll. Need a timer here to delay
+ updates."""
+ if (event.keysym == 'Down' or event.keysym == 'Up'):
+ __listbox1DoLogicCallback(self)
+
+ def __listbox1SingleClick(event):
+ """Call this first when listbox1 is clicked with mouse to put focus
+ into the listbox. Note we call when mouse click is released, not pressed,
+ due to the fact that the listbox does not change the selection until the button
+ is released."""
+ self.listbox1.focus_set()
+ __listbox1DoLogicCallback(self)
+ self.listbox1.bind('<ButtonRelease-1>', __listbox1SingleClick)
+
+ def __listbox1DoLogicCallback(event):
+ """Decides if current selection should be previewed.
+
+ Start by counting items in selection list and if equal to one then
+ show selected font, ignoring if more or less than one. Then also
+ set up buttons logic depending on selection. We bind the FocusIn
+ to this too so button logic and preview gets updated when focus
+ enters the listbox.
+ """
+ # note we are not making use of "self.listbox1.get(ACTIVE)" due to
+ # it not getting the real active name. Always one selection behind
+ # even though we are doing all this in the ButtonRelease event.
+ # Have made a change here. If more than one font name is selected
+ # then we just empty the preview.
+ names = self.listbox1.curselection()
+ if len(names) == 1:
+ selectedFont = self.listbox1.get(names[0])
+ self.__curSelectedItem(selectedFont)
+ else:
+ try:
+ app.previewPanel.delete(previewId)
+ except:
+ pass
+ #else:
+ #selectedFont = self.listbox1.get(ACTIVE)
+ #print selectedFont # for testing
+ #if selectedFont != "":
+ #self.__curSelectedItem(selectedFont)
+
+ # Now do the button logic...
+ self.listbox2.selection_clear(0,END)
+ self.__setUpDownActive(0, 0) # Force a disable if in other box
+ if self.listbox1.size() > 0:
+ self.__setSelButtonsActive(0, 1)
+ else:
+ self.__setSelButtonsActive(0, 0)
+
+ self.listbox1.bind('<FocusIn>', __listbox1DoLogicCallback)
+ self.listbox1.bind('<Any-KeyRelease>', __listbox1KeyRelease)
+
+ def __listbox1DoubleClickCallback(event):
+ """The single click event will fire also when left listbox
+ is double clicked but we are detecting the single click button up event."""
+ self.__listSelectionToRight()
+
+ self.listbox1.bind('<Double-Button-1>', __listbox1DoubleClickCallback)
+
+ # middle button frame assembly
+ self.midbutton_frame = Frame(self.listbox_frame)
+ self.midbutton_frame.grid(row=0, rowspan=2, column=1, sticky=NSEW)
+
+ self.rsingleButton = Button(self.midbutton_frame, state='disabled', text='>', command=self.__rsingleButtonClick)
+ self.rsingleButton.grid(row=0, column=0, padx=5, pady=5, sticky=EW)
+ self.rdoubleButton = Button(self.midbutton_frame, text='>>', command=self.__rdoubleButtonClick)
+ self.rdoubleButton.grid(row=1, column=0, padx=5, pady=5, sticky=EW)
+
+ self.itemupButton = Button(self.midbutton_frame, state='disabled', text='Up', command=self.__itemupButtonClick)
+ self.itemupButton.grid(row=2, column=0, padx=5, pady=5, sticky=EW)
+ self.itemdownButton = Button(self.midbutton_frame, state='disabled', text='Down', command=self.__itemdownButtonClick)
+ self.itemdownButton.grid(row=3, column=0, padx=5, pady=5, sticky=EW)
+
+ self.lsingleButton = Button(self.midbutton_frame, state='disabled', text='<', command=self.__lsingleButtonClick)
+ self.lsingleButton.grid(row=4, column=0, padx=5, pady=5, sticky=EW)
+ self.ldoubleButton = Button(self.midbutton_frame, state='disabled', text='<<', command=self.__ldoubleButtonClick)
+ self.ldoubleButton.grid(row=5, column=0, padx=5, pady=5, sticky=EW)
+
+ # Right hand listbox assembly
+ self.rightListbox_frame = Frame(self.listbox_frame, borderwidth=1, relief=SUNKEN)
+ self.rightListbox_frame.grid(row=1, column=2)
+
+ self.rightLabel = Label(self.listbox_frame, text='Selected Fonts')
+ self.rightLabel.grid(row=0, column=2, sticky=NS)
+
+ self.yScroll2 = Scrollbar(self.rightListbox_frame, orient=VERTICAL)
+ self.yScroll2.grid(row=0, column=1, sticky=NS)
+ self.xScroll2 = Scrollbar(self.rightListbox_frame, orient=HORIZONTAL)
+ self.xScroll2.grid(row=1, column=0, sticky=EW)
+
+ self.listbox2 = Listbox(self.rightListbox_frame,
+ xscrollcommand=self.xScroll2.set,
+ yscrollcommand=self.yScroll2.set,
+ selectmode=EXTENDED,
+ height=20, width=40)
+ self.listbox2.grid(row=0, column=0, sticky=NSEW)
+ self.xScroll2['command'] = self.listbox2.xview
+ self.yScroll2['command'] = self.listbox2.yview
+
+ def __listbox2SingleClick(event):
+ """Similar to __listbox1SingleClick()."""
+ self.listbox2.focus_set()
+ __listbox2DoLogicCallback(self)
+ self.listbox2.bind('<ButtonRelease-1>', __listbox2SingleClick)
+
+ def __listbox2KeyRelease(event):
+ if (event.keysym == 'Down' or event.keysym == 'Up'):
+ __listbox2DoLogicCallback(self)
+
+ def __listbox2DoLogicCallback(event):
+ """Similar to __listbox1DoLogicCallback()."""
+ names = self.listbox2.curselection()
+ if len(names) == 1:
+ selectedFont = self.listbox2.get(names[0])
+ self.__curSelectedItem(selectedFont)
+ else:
+ try:
+ app.previewPanel.delete(previewId)
+ except:
+ pass
+
+ # Now do the button logic...
+ self.listbox1.selection_clear(0,END)
+ self.__testUpDownState()
+ if self.listbox2.size() > 0:
+ self.__setSelButtonsActive(1, 0)
+ else:
+ self.__setSelButtonsActive(0, 0)
+ self.listbox2.bind('<FocusIn>', __listbox2DoLogicCallback)
+ self.listbox2.bind('<Any-KeyRelease>', __listbox2KeyRelease)
+
+ def __listbox2DoubleClickCallback(event):
+ """Similar to __listbox1DoubleClickCallback()."""
+ self.__listSelectionToLeft()
+ self.listbox2.bind('<Double-Button-1>', __listbox2DoubleClickCallback)
+
+ # now draw the bottom font preview frame if required...
+ if showPreviewPanel:
+ self.preview_frame = Frame(self)
+ self.preview_frame.grid(row=1, column=0, sticky=EW)
+ self.previewPanel = Canvas(self.preview_frame, height=60, bg='white', bd=2, relief=SUNKEN)
+ self.previewPanel.pack(fill=X)
+
+ # now draw the bottom controls frame...
+ self.controls_frame = Frame(self)
+ self.controls_frame.grid(row=2, column=0, sticky=EW)
+
+ # create a container...
+ self.button_frame1 = Frame(self.controls_frame, bd=1, relief=RIDGE)
+ self.button_frame1.grid(row=0, column=0, padx=10, pady=2)
+ # create and add page number selection button...
+ self.__wantPageNum = IntVar()
+ self.pagenumSelect = Checkbutton(self.button_frame1, text='Print page numbers', variable=self.__wantPageNum, offvalue=0, onvalue=1, command=self.__pageNumberSelectButtonClick)
+ self.pagenumSelect.grid(row=0, column=0, padx=0, sticky=W)
+
+ # create a container...
+ self.button_frame2 = Frame(self.controls_frame, bd=1, relief=RIDGE)
+ self.button_frame2.grid(row=0, column=1, padx=10, pady=2)
+ # create and add the TOC selector...
+ self.__wantToc = IntVar()
+ self.tocSelect = Checkbutton(self.button_frame2, text='Print table of contents', variable=self.__wantToc, offvalue=0, onvalue=1, command=self.__tocSelectButtonClick)
+ self.tocSelect.grid(row=0, column=0, padx=0, sticky=W)
+ # create and add page one on first selector...
+ self.__wantPageOneOnFirst = IntVar()
+ self.btnPageOneOnFirst = Checkbutton(self.button_frame2, text='Page count includes TOC', variable=self.__wantPageOneOnFirst, offvalue=0, onvalue=1, command=self.__wantPageOneOnFirstClick)
+ self.btnPageOneOnFirst.grid(row=1, column=0, padx=0, sticky=W)
+
+ # create a container...
+ self.button_frame3 = Frame(self.controls_frame, bd=1, relief=RIDGE)
+ self.button_frame3.grid(row=0, column=2, padx=10, pady=2)
+ # create and add the binding offset...
+ self.__wantBindingOffset = IntVar()
+ self.bindingoffsetSelect = Checkbutton(self.button_frame3, text='Extra offset for binding', variable=self.__wantBindingOffset, offvalue=0, onvalue=1, command=self.__bindingoffsetSelectButtonClick)
+ self.bindingoffsetSelect.grid(row=0, column=0, sticky=W)
+ # create and add the double sided selection buttons...
+ self.__wantDoubleSided = IntVar()
+ self.doublesidedSelect = Checkbutton(self.button_frame3, text='Double sided pages', variable=self.__wantDoubleSided, offvalue=0, onvalue=1, command=self.__doubleSidedSelectButtonClick)
+ self.doublesidedSelect.grid(row=1, column=0, rowspan=2, sticky=W)
+
+ # now the ok and cancel buttons...
+ self.cancelButton = Button(self.controls_frame, text='Cancel', command=self.__cancelButtonClick)
+ self.cancelButton.grid(row=0, column=3, padx=5)
+ self.okButton = Button(self.controls_frame, text='OK', state='disabled', command=self.__okButtonClick)
+ self.okButton.grid(row=0, column=4, padx=5)
+
+ # now create the bottom status bar frame and contents...
+ self.status_frame = Frame(self)
+ self.status_frame.grid(row=3, column=0, sticky=E+W)
+ self.status0 = Label(self.status_frame, bd=1, relief=SUNKEN, anchor=W)
+ self.status0.pack(side=LEFT)
+ self.status1 = Label(self.status_frame, bd=1, relief=SUNKEN, anchor=W)
+ self.status1.pack(side=LEFT)
+ self.status2 = Label(self.status_frame, bd=1, relief=SUNKEN, anchor=W)
+ self.status2.pack(side=LEFT)
+ self.status3 = Label(self.status_frame, bd=1, relief=SUNKEN, anchor=W)
+ self.status3.pack(side=LEFT)
+ self.statusPaperSize = Label(self.status_frame, bd=1, relief=SUNKEN, anchor=W)
+ self.statusPaperSize.pack(fill=X)
+
+ def statusbarUpdate(self):
+ """Draws the status bar contents.
+
+ Note "draw_selection()" does a dummy run to count the amount of sample
+ blocks on a sheet.
+ TODO: Statusbar setting and recalculation should be separated. Just recalc
+ and refresh panels as required instead of all of them each time.
+ """
+ available = self.listbox1.size()
+ selected = self.listbox2.size()
+ size = FloatType(selected)
+ blocksPerSheet = draw_selection(scribus.getFontNames(), 1)
+ value = size / blocksPerSheet
+ pages = IntType(value) # Get whole part of number
+ value = value - pages # Remove whole number part
+ if value > 0: # Test remainder
+ pages = pages + 1 # Had remainder so add a page
+ self.status0['text'] = 'Fonts available: %s ' % (available + selected)
+ self.status1['text'] = 'Fonts selected: %s ' % selected
+ self.status2['text'] = 'Sheets required: %s ' % pages
+ self.status3['text'] = 'Fonts per sheet: %s ' % blocksPerSheet
+ self.statusPaperSize['text'] = 'Paper size: %s ' % userPrefs['paperSize']
+
+ def __listSelectionToRight(self):
+ toMoveRight = ListType(self.listbox1.curselection())
+ self.listbox1.selection_clear(0,END)
+ toMoveRight.reverse() # reverse list so we delete from bottom of listbox first
+ tempList = []
+ for i in toMoveRight:
+ tempList.insert(0,self.listbox1.get(i)) # gets the actual strings (reverse again)
+ self.listbox1.delete(i)
+ for j in tempList:
+ self.listbox2.insert(END, j)
+ self.__setButtonsState()
+ self.__setSelButtonsActive(0, 0)
+ self.statusbarUpdate()
+
+ def __listSelectionToLeft(self):
+ toMoveLeft = ListType(self.listbox2.curselection())
+ toMoveLeft.reverse()
+ self.listbox2.selection_clear(0,END)
+ for i in toMoveLeft:
+ self.listbox1.insert(END, self.listbox2.get(i)) # Insert it at the end
+ self.listbox2.delete(i)
+ fontList = ListType(self.listbox1.get(0, END)) # Copy contents to a list type
+ self.listbox1.delete(0, END) # Remove all contents
+ fontList.sort() # Use sort method of list
+ for j in fontList:
+ self.listbox1.insert(END, j) # Replace with sorted version
+ self.__setButtonsState()
+ self.__setSelButtonsActive(0, 0)
+ self.statusbarUpdate()
+
+ def __listAllToRight(self):
+ fontList = self.listbox1.get(0, END) # Get each font name into a list
+ for i in fontList:
+ self.listbox2.insert(END, i) # Copy each one
+ self.listbox1.delete(0, END) # All done so empty the left listbox
+ self.__setButtonsState()
+ self.__setSelButtonsActive(0, 0)
+ self.statusbarUpdate()
+
+ def __listAllToLeft(self):
+ """Moves all selected fonts back to the left hand pane.
+
+ Note we just clear both panes then reload the left listbox in correct
+ order from scratch as this is probably quicker than moving each
+ item individually.
+ """
+ self.listbox1.delete(0, END)
+ fontList = scribus.getFontNames()
+ fontList.sort()
+ for i in fontList:
+ self.listbox1.insert(END, i)
+ self.listbox2.delete(0, END)
+ self.__setButtonsState()
+ self.__setSelButtonsActive(0, 0)
+ self.statusbarUpdate()
+
+ def __setSelButtonsActive(self, selToRight, selToLeft):
+ # The "selection" buttons are the ones with ">" and "<" on them
+ if selToRight == 1:
+ self.lsingleButton['state'] = NORMAL
+ else:
+ self.lsingleButton['state'] = DISABLED
+ if selToLeft == 1:
+ self.rsingleButton['state'] = NORMAL
+ else:
+ self.rsingleButton['state'] = DISABLED
+
+ def __setAllButtonsActive(self, allToRight, allToLeft):
+ # The "all" buttons are the ones with ">>" and "<<" on them
+ if allToRight == 1:
+ self.rdoubleButton['state'] = NORMAL
+ else:
+ self.rdoubleButton['state'] = DISABLED
+ if allToLeft == 1:
+ self.ldoubleButton['state'] = NORMAL
+ else:
+ self.ldoubleButton['state'] = DISABLED
+
+ def __setButtonsState(self):
+ if self.listbox2.size() > 0 and self.listbox1.size() > 0:
+ self.__setAllButtonsActive(1, 1)
+ self.okButton['state'] = NORMAL
+ elif self.listbox2.size() == 0:
+ self.__setAllButtonsActive(1, 0)
+ self.okButton['state'] = DISABLED
+ elif self.listbox1.size() == 0:
+ self.__setAllButtonsActive(0, 1)
+ self.okButton['state'] = NORMAL
+
+ def __itemUp(self):
+ """Test if one item is selected then move it up one position."""
+ selection = self.listbox2.curselection()
+ if len(selection) == 1:
+ indexId = IntType(selection[0]) # Get the first (only) item as integer type
+ if indexId > 0:
+ fontString = self.listbox2.get(indexId)
+ self.listbox2.delete(indexId)
+ newPos = indexId - 1
+ self.listbox2.selection_clear(0, END)
+ self.listbox2.insert(newPos, fontString)
+ self.listbox2.see(newPos - 10) # Scrolls listbox automatically into view if req.
+ self.listbox2.selection_set(newPos)
+ self.listbox2.activate(newPos) # make focus follow selection
+ self.__testUpDownState() # note tests only after an item has been moved
+
+ def __itemDown(self):
+ """Test if one item is selected then move it down one position."""
+ limit = self.listbox2.size()
+ selection = self.listbox2.curselection()
+ if len(selection) == 1:
+ indexId = IntType(selection[0])
+ if indexId < limit - 1:
+ fontString = self.listbox2.get(indexId)
+ self.listbox2.delete(indexId)
+ newPos = indexId + 1
+ self.listbox2.selection_clear(0, END)
+ self.listbox2.insert(newPos, fontString)
+ self.listbox2.see(newPos + 10)
+ self.listbox2.selection_set(newPos)
+ self.listbox2.activate(newPos) # make focus follow selection
+ self.__testUpDownState()
+
+ def __setUpDownActive(self, up, down):
+ """Just sets the buttons active or inactive.
+
+ See testUpDown() for the actual evaluation
+ """
+ if up == 1:
+ self.itemupButton['state'] = NORMAL
+ else:
+ self.itemupButton['state'] = DISABLED
+ if down == 1:
+ self.itemdownButton['state'] = NORMAL
+ else:
+ self.itemdownButton['state'] = DISABLED
+
+ def __testUpDownState(self):
+ """Only enable the up and down buttons when just a single item is selected.
+
+ Enable should be applied to up, down or both depending on its
+ position in the listbox. At all other times disable both.
+ """
+ # Get a count of how many items are currently selected...
+ selection = list(self.listbox2.curselection())
+ tcount = 0
+ for sel in selection:
+ tcount = tcount + 1
+
+ position = 0
+ if tcount == 1:
+ position = IntType(selection[0])
+
+ # If one selected and there is more than one item in the listbox then ok...
+ if tcount == 1 and self.listbox2.size() > 1:
+ # Now test the position of the selected line...
+ if position > 0 and position < self.listbox2.size() - 1: # Both
+ self.__setUpDownActive(1, 1)
+ # If not one less or lesser from the bottom (listbox.count-1?) then gray the down button.
+ elif position == self.listbox2.size() - 1: # Up only
+ self.__setUpDownActive(1, 0)
+ # If not one or more from the top then gray up button.
+ elif position == 0: # Down only
+ self.__setUpDownActive(0, 1)
+ else:
+ self.__setUpDownActive(0, 0)
+
+ def __curSelectedItem(self, selectedFont):
+ """Send the selected font to the preview function if preview available."""
+ if showPreviewPanel:
+ preview_font(self, selectedFont)
+
+ # create the button events...
+ def __rsingleButtonClick(self):
+ self.__listSelectionToRight()
+
+ def __rdoubleButtonClick(self):
+ self.__listAllToRight()
+
+ def __lsingleButtonClick(self):
+ self.__listSelectionToLeft()
+ self.__testUpDownState()
+
+ def __ldoubleButtonClick(self):
+ self.__listAllToLeft()
+ self.__testUpDownState()
+
+ def __itemupButtonClick(self):
+ self.__itemUp()
+
+ def __itemdownButtonClick(self):
+ self.__itemDown()
+
+ def __tocSelectButtonClick(self):
+ userPrefs['wantTOC'] = self.__wantToc.get()
+ if userPrefs['wantTOC']:
+ self.btnPageOneOnFirst['state'] = NORMAL
+ else:
+ self.btnPageOneOnFirst['state'] = DISABLED
+
+ def __pageNumberSelectButtonClick(self):
+ userPrefs['wantPageNumbers'] = self.__wantPageNum.get()
+
+ def __bindingoffsetSelectButtonClick(self):
+ userPrefs['wantBindingOffset'] = self.__wantBindingOffset.get()
+ dD.update(set_page_geometry(dD, geometriesList, userPrefs['paperSize'], userPrefs['wantBindingOffset']))
+
+ def __doubleSidedSelectButtonClick(self):
+ userPrefs['wantDoubleSided'] = self.__wantDoubleSided.get()
+
+ def __wantPageOneOnFirstClick(self):
+ userPrefs['wantPageOneOnFirst'] = self.__wantPageOneOnFirst.get()
+
+ def __cancelButtonClick(self):
+ """We exit the app here if user presses cancel."""
+ self.master.destroy()
+
+ def __okButtonClick(self):
+ """User presses ok, so lets create the pages."""
+ save_user_conf(CONFIG_PATH)
+ draw_selection(self.listbox2.get(0, END), 0)
+ self.master.destroy()
+
+ def __configurationDlgShow(self):
+ """Opens the configuration dialog where user can set up the options"""
+ configs = ConfigurationDialog(self)
+ self.statusbarUpdate()
+
+ def __saveCurrentSettingsAsDefaults(self):
+ """Stores current settings as defaults."""
+ defaultPrefs.update(userPrefs)
+ save_user_conf(CONFIG_PATH)
+
+ def __restoreCurrentSettingsFromDefault(self):
+ """Restores current settings from defaults."""
+ userPrefs.update(defaultPrefs)
+ self.initialiseWidgets()
+ self.statusbarUpdate()
+
+ def initialiseWidgets(self):
+ if userPrefs['wantPageNumbers']:
+ self.pagenumSelect.select()
+ else:
+ self.pagenumSelect.deselect()
+ if userPrefs['wantTOC']:
+ self.tocSelect.select()
+ self.btnPageOneOnFirst['state'] = NORMAL
+ else:
+ self.tocSelect.deselect()
+ self.btnPageOneOnFirst['state'] = DISABLED
+ if userPrefs['wantBindingOffset']:
+ self.bindingoffsetSelect.select()
+ else:
+ self.bindingoffsetSelect.deselect()
+ if userPrefs['wantDoubleSided']:
+ self.doublesidedSelect.select()
+ else:
+ self.doublesidedSelect.deselect()
+ if userPrefs['wantPageOneOnFirst']:
+ self.btnPageOneOnFirst.select()
+ else:
+ self.btnPageOneOnFirst.deselect()
+
+ def __aboutDlgShow(self):
+ """Brings up a dialog with support url etc."""
+ about = AboutDialog(self)
+
+
+def setup_tk():
+ """Create and setup the Tkinter app."""
+ root = Tk()
+ app = Application(root)
+ app.master.title(WINDOW_TITLE)
+
+ # now get a list of all the fonts Scribus knows about...
+ fontList = scribus.getFontNames()
+ fontList.sort()
+ # and load the list into the GUI listbox...
+ for i in fontList:
+ app.listbox1.insert(END, i)
+ app.sampleBlocksPerPage = draw_selection(scribus.getFontNames(), 1)
+ # now set the status bar message...
+ app.statusbarUpdate()
+ # set up widgets using data from userPrefs...
+ app.initialiseWidgets()
+ return app
+
+def initialisation():
+ """Test for suitable fonts and on success creates tkinter app."""
+ try:
+ dD['bookstyleFixedFont'] = set_font_fixed(fontsListFixed)
+ dD['bookstylePropFont'] = set_font_proportional(fontsListProportional)
+ except:
+ scribus.messageBox('Font problem',
+ '%s' % sys.exc_info()[1],
+ scribus.ICON_WARNING)
+ sys.exit(1)
+ # load users saved defaults...
+ restore_user_conf(CONFIG_PATH)
+ # get and set the initial paper size to match default radiobutton selection...
+ dD.update(set_page_geometry(dD, geometriesList, userPrefs['paperSize'], userPrefs['wantBindingOffset']))
+ # Made it this far so its time to create our Tkinter app...
+ app = setup_tk()
+ # now show the main window and wait for user to do something...
+ app.mainloop()
+
+
+def main(argv):
+ """Application initialization, font checks and initial setup."""
+ initialisation()
+
+
+def main_wrapper(argv):
+ """The main_wrapper() function disables redrawing, sets a sensible generic
+ status bar message, and optionally sets up the progress bar. It then runs
+ the main() function. Once everything finishes it cleans up after the main()
+ function, making sure everything is sane before the script terminates."""
+ try:
+ scribus.statusMessage('Running script...')
+ scribus.progressReset()
+ main(argv)
+ finally:
+ # Exit neatly even if the script terminated with an exception,
+ # so we leave the progress bar and status bar blank and make sure
+ # drawing is enabled.
+ if scribus.haveDoc():
+ scribus.setRedraw(True)
+ scribus.statusMessage('')
+ scribus.progressReset()
+
+
+# This code detects if the script is being run as a script, or imported as a module.
+# It only runs main() if being run as a script. This permits you to import your script
+# and control it manually for debugging.
+if __name__ == '__main__':
+ main_wrapper(sys.argv)
+
diff --git a/scribus/plugins/scriptplugin/scripts/InfoBox.py b/scribus/plugins/scriptplugin/scripts/InfoBox.py
new file mode 100644
index 0000000..f1050e1
--- /dev/null
+++ b/scribus/plugins/scriptplugin/scripts/InfoBox.py
@@ -0,0 +1,163 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# ****************************************************************************
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# ****************************************************************************
+
+
+"""
+(C) 2005 by Thomas R. Koll, <tomk32@gmx.de>, http://verlag.tomk32.de
+
+(c) 2008, 2010 modifications, additional features, and some repair
+ by Gregory Pittman
+
+A simple script for exact placement of a frame (infobox)
+over the current textbox, asking the user for the width
+of the infobox and in which column to place it.
+
+Some enhancements:
+
+* You can now create a text frame or an image frame, and also load
+an image.
+
+* More than one infobox can be added to a text frame by repeatedly running
+ the script (ie, no name conflicts occur).
+
+* Height and Y-Pos of top of infobox can be specified.
+
+* Works with any page unit - pts, mm, in, and picas, cm, and even ciceros.
+
+* Infobox has Text Flows Around Frame activated, also
+ Scale Image to Frame for images.
+
+USAGE
+
+Select a textframe, start the script and have phun
+Default name for the infobox is 'infobox' + name_of_selected_frame,
+but this can be changed.
+
+
+"""
+
+try:
+ import scribus
+except ImportError:
+ print "Unable to import the 'scribus' module. This script will only run within"
+ print "the Python interpreter embedded in Scribus. Try Script->Execute Script."
+ sys.exit(1)
+
+def main(argv):
+ unit = scribus.getUnit()
+ units = [' pts','mm',' inches',' picas','cm',' ciceros']
+ unitlabel = units[unit]
+ if scribus.selectionCount() == 0:
+ scribus.messageBox('Scribus - Script Error',
+ "There is no object selected.\nPlease select a text frame and try again.",
+ scribus.ICON_WARNING, scribus.BUTTON_OK)
+ sys.exit(2)
+ if scribus.selectionCount() > 1:
+ scribus.messageBox('Scribus - Script Error',
+ "You have more than one object selected.\nPlease select one text frame and try again.",
+ scribus.ICON_WARNING, scribus.BUTTON_OK)
+ sys.exit(2)
+ textbox = scribus.getSelectedObject()
+ pageitems = scribus.getPageItems()
+ boxcount = 1
+ for item in pageitems:
+ if (item[0] == textbox):
+ if (item[1] != 4):
+ scribus.messageBox('Scribus - Script Error',
+ "This is not a textframe. Try again.", scribus.ICON_WARNING, scribus.BUTTON_OK)
+ sys.exit(2)
+
+# While we're finding out what kind of frame is selected, we'll also make sure we
+# will come up with a unique name for our infobox frame - it's possible we may want
+# more than one for a multicolumn frame.
+ if (item[0] == ("infobox" + str(boxcount) + textbox)):
+ boxcount += 1
+ left, top = scribus.getPosition(textbox)
+ o_width, o_height = scribus.getSize(textbox)
+ o_cols = int(scribus.getColumns(textbox))
+ o_gap = scribus.getColumnGap(textbox)
+
+ columns_width = 0
+ column_pos = 0
+ o_colwidth = (o_width - ((o_cols - 1) * o_gap)) / o_cols
+ if (o_cols > 1):
+ while (columns_width > o_cols or columns_width < 1):
+ columns_width = scribus.valueDialog('Width',
+ 'How many columns width shall the '+
+ 'box be (max ' + str(o_cols) + ')?','1')
+ columns_width = int(columns_width)
+ if (columns_width < o_cols):
+ max = o_cols - columns_width
+ while (column_pos <= max and column_pos <= 1):
+ column_pos = scribus.valueDialog('Placement',
+ 'In which column do you want '
+ 'to place the box (1 to ' +
+ str(o_cols) + ')?','1')
+ column_pos = int(column_pos) - 1
+ if (o_cols == 1):
+ columns_width = 1
+ new_height = 0
+ while (new_height == 0):
+ new_height = scribus.valueDialog('Height','Your frame height is '+ str(o_height) +
+ unitlabel +'. How tall\n do you want your ' +
+ 'infobox to be in '+ unitlabel +'?\n If you load an image, height will be\n calculated, so the value here does not\n matter.', str(o_height))
+ new_top = -1
+ while (new_top < 0):
+ new_top = scribus.valueDialog('Y-Pos','The top of your infobox is currently\n'+ str(top) +
+ unitlabel +'. Where do you want \n' +
+ 'the top to be in '+ unitlabel +'?', str(top))
+ framename = scribus.valueDialog('Name of Frame','Name your frame or use this default name',"infobox" + str(boxcount) + textbox)
+ frametype = 'text'
+ frametype = scribus.valueDialog('Frame Type','Change to anything other\n than "text" for image frame.\nEnter "imageL" to also load an image',frametype)
+ new_width = columns_width * o_colwidth + (columns_width-1) * o_gap
+ new_left = left + ((column_pos) * o_colwidth) + ((column_pos) * o_gap)
+ if (frametype == 'text'):
+ new_textbox = scribus.createText(new_left, float(new_top), new_width, float(new_height),framename)
+ scribus.setColumnGap(0, new_textbox)
+ scribus.setColumns(1, new_textbox)
+ scribus.textFlowMode(new_textbox, 1)
+ else:
+ if (frametype == 'imageL'):
+ imageload = scribus.fileDialog('Load image','Images(*.jpg *.png *.tif *.JPG *.PNG *.jpeg *.JPEG *.TIF)',haspreview=1)
+ new_image = scribus.createImage(new_left, float(new_top), new_width, float(new_height),framename)
+ scribus.loadImage(imageload, new_image)
+ scribus.messageBox('Please Note',"Your frame will be created once you click OK.\n\nUse the Context Menu to Adjust Frame to Image.\n\nIf your image does not fill the width completely,\nstretch the frame vertically first.",scribus.BUTTON_OK)
+ else:
+ new_image = scribus.createImage(new_left, float(new_top), new_width, float(new_height),framename)
+ scribus.textFlowMode(new_image, 1)
+ scribus.setScaleImageToFrame(scaletoframe=1, proportional=1, name=new_image)
+if __name__ == '__main__':
+ # This script makes no sense without a document open
+ if not scribus.haveDoc():
+ scribus.messageBox('Scribus - Script Error', "No document open", scribus.ICON_WARNING, scribus.BUTTON_OK)
+ sys.exit(1)
+ # Disable redraws
+ scribus.setRedraw(False)
+ # Run the main script, ensuring redraws are re-enabled even if the
+ # script aborts with an exception, and don't fail with an exception
+ # even if the document is closed while the script runs.
+ try:
+ main(sys.argv)
+ finally:
+ try:
+ scribus.setRedraw(True)
+ except:
+ pass
+
diff --git a/scribus/plugins/scriptplugin/scripts/NEWS b/scribus/plugins/scriptplugin/scripts/NEWS
new file mode 100644
index 0000000..f81f813
--- /dev/null
+++ b/scribus/plugins/scriptplugin/scripts/NEWS
@@ -0,0 +1,40 @@
+New since 0.7 series:
+
+ Now able to do a dummy run to calculate and report the amount of samples
+ that will fit on a page. This enables the script to correctly calculate
+ how many sheets will be required. Previously it was always assumed that
+ there would be 3 sample blocks on a sheet. This is now not always the case.
+
+ Sample rows can be selected or unselected to save on paper. The settings are
+ automatically saved when changed and can be set as user defaults.
+
+ User can choose to have page numbers count from first page of the toc instead
+ of the first page of samples. This can be helpful if wanting to quickly look
+ up a font in the toc and then using the Scribus page navigator dialog to go to
+ the actual page on the screen to view it without printing it out.
+
+ Added initial support for a sample paragraph. The sample paragraph defaults
+ to "off" due to the amount of space it uses on the page.
+
+New since v0.6.1:
+
+ Added a font sample preview panel. This will only be displayed if certain system
+ requirements are met. Otherwise the panel will be hidden.
+ Changed version numbers to accomodate parallel releases using other widget sets.
+ Tkinter versions will now have the letters "tk" appended after the version number, a
+ qt version would be "qt". Note that a qt version will not be appearing until issues will PyQt
+ can be resolved.
+
+New since V0.5a:
+
+ Optional Page Numbers.
+ Optional Table of Contents creation.
+ Added an optional binding offset. Leaves extra space for the binding edge.
+ Added Double sided paper facility. Inserts a blank page after table of contents
+ if required, to force the main sample pages to always start on an odd page
+ number. This also flips the binding offset to the other side when printing the
+ even numbered side.
+ Better layouts.
+ Has more built in default font options for headers, table of contents and
+ sample labels.
+ Users can now select more than one font at a time in the list boxes.
diff --git a/scribus/plugins/scriptplugin/scripts/ReadMe b/scribus/plugins/scriptplugin/scripts/ReadMe
new file mode 100644
index 0000000..df8aa61
--- /dev/null
+++ b/scribus/plugins/scriptplugin/scripts/ReadMe
@@ -0,0 +1 @@
+This folder contains the official Scripts for Scribus
diff --git a/scribus/plugins/scriptplugin/scripts/TODO b/scribus/plugins/scriptplugin/scripts/TODO
new file mode 100644
index 0000000..ec172b1
--- /dev/null
+++ b/scribus/plugins/scriptplugin/scripts/TODO
@@ -0,0 +1,13 @@
+TODO:
+
+Make a PDF sample page for the web site using three example fonts such as...
+Utopia, Bitstream Charter Luxi, Helvetica or any of the Web fonts
+ - Trebuchet, Times *New * Roman, Georgia
+
+Need improvments to the clean up code to insure that temp images are removed
+from .scribus folder.
+
+Improve the Listbox events coding.
+
+Continual holding of Up or Down keys causes preview to be redrawn rapidly. This causes
+a number of problems. Needs a timer to delay redraws when scrolling.
diff --git a/scribus/plugins/scriptplugin/scripts/color2csv.py b/scribus/plugins/scriptplugin/scripts/color2csv.py
new file mode 100644
index 0000000..d4bf10f
--- /dev/null
+++ b/scribus/plugins/scriptplugin/scripts/color2csv.py
@@ -0,0 +1,160 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+ABOUT THIS SCRIPT:
+
+Export Scribus Colors to CSV
+
+color2csv.py allows a user to export the colors of a given scribus document in a csv file. The file will be a text file with comma seperated values in the following format:
+"colorname", c,m,y,k
+
+If there is a document opened in scribus, color2csv uses this document as color source.
+If there is no document opened in scribus, color2csv displays a file open dialog to allow the user to chose a scribus file to get the colors from.
+
+Use csv2color to import the colors into a scribus document from a csv file.
+
+############################
+
+LICENSE:
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+Author: Sebastian Stetter
+
+please report bugs to: scribusscript@sebastianstetter.de
+"""
+from __future__ import division
+import sys
+
+__version__=1.0
+
+try:
+ # Please do not use 'from scribus import *' . If you must use a 'from import',
+ # Do so _after_ the 'import scribus' and only import the names you need, such
+ # as commonly used constants.
+ import scribus
+except ImportError,err:
+ print "This Python script is written for the Scribus scripting interface."
+ print "It can only be run from within Scribus."
+ sys.exit(1)
+
+#########################
+# YOUR IMPORTS GO HERE #
+#########################
+import csv
+import os
+#define some variables
+
+def getColorsFromDoc():
+ """returns a list ("name", c,y,m,k)
+ get all the colors of that doc. """
+ #get a list of al the colornames
+ scribus.statusMessage("Reading Colors...")
+
+ try:
+ colorlist = scribus.getColorNames()
+ scribus.progressTotal(len(colorlist))
+ i=0
+ colordata=[]
+ for color in colorlist:
+ colorvalues=scribus.getColor(color)
+ c=int(colorvalues[0]/2.55) #convert values from 0-255 to 0-100
+ m=int(colorvalues[1]/2.55)
+ y=int(colorvalues[2]/2.55)
+ k=int(colorvalues[3]/2.55)
+ name=color.strip() #eliminate leading and tailing whitespace
+ cd = [name,c ,m,y,k]
+ colordata.append(cd)
+ i=i+1
+ scribus.progressSet(i)
+
+ return colordata
+ except:
+ scribus.messageBox("color2csv", "Can not retrieve colors - There is no Document", icon=scribus.ICON_WARNING)
+ sys.exit()
+
+
+def writeColorCsvFile(filename, colorlist):
+ """writes all the colors to a csv file"""
+ scribus.statusMessage("Writing colors to csv file...")
+ scribus.progressTotal(len(colorlist))
+ i=0
+ try:
+ csvwriter=csv.writer(file(filename, "w"), quoting=csv.QUOTE_NONNUMERIC)
+ for line in colorlist:
+ csvwriter.writerow(line)
+ i=i+1
+ scribus.progressSet(i)
+ except:
+ scribus.messageBox("color2csv", "Could not write file!", icon=scribus.ICON_WARNING)
+ sys.exit()
+
+def main(argv):
+ """Main method - here we check if we have a doc - else we open one. we get all the colors and write them to a csv file."""
+ if scribus.haveDoc(): #DOC OPEN
+ #get colors, get filename, write stuff
+ cols = getColorsFromDoc()
+ filename = scribus.fileDialog("color2csv: Save csv color file", defaultname="colors.csv", issave=True , haspreview=False)
+
+ #@TODO: optimize path checking
+ if filename !="":
+ if os.path.exists(filename): #make shure we don't accidentaly overwrite existing files
+ answer= scribus.messageBox("color2csv", "File already exists! \n do you want to overwrite it?", icon=scribus.ICON_WARNING, button1=scribus.BUTTON_YES, button2=scribus.BUTTON_ABORT)
+ if answer == scribus.BUTTON_YES:
+ writeColorCsvFile(filename, cols)
+ else:
+ sys.exit()
+ else:
+ writeColorCsvFile(filename, cols)
+ else:
+ sys.exit()
+ else: # NO DOC OPEN - open one!
+ scribusfile = scribus.fileDialog("color2csv: Open scribus file", "Scribus files(*.sla *.SLA *.sla.gz *.SLA.GZ)")
+ if scribusfile !="":
+ try:
+ scribus.openDoc(scribusfile)
+ except:
+ scribus.messageBox("color2csv", "Could not open file!")
+ sys.exit()
+ #get colors, get filename, write stuff
+ cols = getColorsFromDoc()
+ filename = scribus.fileDialog("color2csv: Save csv color file", defaultname="colors.csv", issave=True )
+ writeColorCsvFile(filename, cols)
+ else:
+ sys.exit()
+
+def main_wrapper(argv):
+ """The main_wrapper() function disables redrawing, sets a sensible generic
+ status bar message, and optionally sets up the progress bar. It then runs
+ the main() function. Once everything finishes it cleans up after the main()
+ function, making sure everything is sane before the script terminates."""
+ try:
+ #scribus.statusMessage("Running script...")
+ #scribus.progressReset()
+ main(argv)
+ finally:
+ # Exit neatly even if the script terminated with an exception,
+ # so we leave the progress bar and status bar blank and make sure
+ # drawing is enabled.
+ if scribus.haveDoc():
+ scribus.setRedraw(True)
+ scribus.statusMessage("")
+ scribus.progressReset()
+
+# This code detects if the script is being run as a script, or imported as a module.
+# It only runs main() if being run as a script. This permits you to import your script
+# and control it manually for debugging.
+if __name__ == '__main__':
+ main_wrapper(sys.argv)
diff --git a/scribus/plugins/scriptplugin/scripts/csv2color.py b/scribus/plugins/scriptplugin/scripts/csv2color.py
new file mode 100644
index 0000000..0c4011d
--- /dev/null
+++ b/scribus/plugins/scriptplugin/scripts/csv2color.py
@@ -0,0 +1,187 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+ABOUT THIS SCRIPT:
+
+Import Colors from a CSV file to Scribus
+
+csv2color.py allows a user to import colors from a given csv file into a scribus document.
+The file must be a text file with comma seperated values in the following format:
+
+"colorname", c,m,y,k
+
+There must be a document opend in scribus where the colors can be defined in.
+If the csv contanins one or more color names that already exist in the document, the colors will be imported with a `*` as prefix.
+
+This script is especially helpfull if you want to use CMYK color representations of color systems like HKS, Pantone or RAL in Scribus. Lots of such CMYK translation tables can be found on the Web.
+One can easily copy such a table into a text file, save it in the obove described format and import it into a scribus document.
+
+Use color2csv to export the colors from a scribus document into a csv file.
+
+############################
+
+LICENSE:
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+Author: Sebastian Stetter
+
+please report bugs to: scribusscript@sebastianstetter.de
+"""
+from __future__ import division
+import sys
+
+__version__=1.1
+
+
+try:
+ # Please do not use 'from scribus import *' . If you must use a 'from import',
+ # Do so _after_ the 'import scribus' and only import the names you need, such
+ # as commonly used constants.
+ import scribus
+except ImportError,err:
+ print "This Python script is written for the Scribus scripting interface."
+ print "It can only be run from within Scribus."
+ sys.exit(1)
+
+#########################
+# YOUR IMPORTS GO HERE #
+#########################
+import csv
+import os
+
+PREFIX="*"
+
+def checkValue(c, m, y, k):
+ """returns true if the cmyk values are between 0 and 255"""
+ MINVAL=0
+ MAXVAL=255
+ valueOk=True
+ for val in c, m, y, k:
+ if val >=MINVAL and val <=255:
+ pass
+ else:
+ valueOk=False
+
+ return valueOk
+
+def getColorsFromCsv(filename):
+ """get colors from csv file and return a list with name and cmyk 255 values"""
+ csvreader=csv.reader(file(filename))
+
+ csvcolors=[]
+ i=0
+ for row in csvreader:
+ name=row[0]
+ name=name.strip()
+ c=int(row[1] )* 2.55
+ c=int(c)
+ m=int(row[2] )* 2.55
+ m=int(m)
+ y=int(row[3] )* 2.55
+ y=int(y)
+ k=int(row[4] )* 2.55
+ k=int(k)
+ if checkValue(c, m, y, k) ==False:
+ scribus.messageBox("csv2color", "At least one CMYK value in your csv file is not correct \n(must be between 0 and 100)\nAborting script - nothing imported.", icon=scribus.ICON_WARNING)
+ sys.exit()
+ else:
+ pass
+ color=(name, c, m, y, k)
+ csvcolors.append(color)
+ i=i+1
+ return csvcolors
+
+def getColorDict():
+ """get the colors that already exist from the opened Document and return a dictionary"""
+ scribus.statusMessage("Reading existing colors...")
+ colornames = scribus.getColorNames()
+ scribus.progressTotal(len(colornames))
+ i=0
+ colordict={}
+ for name in colornames:
+ colordict[name]=None
+ i=i+1
+ scribus.progressSet(i)
+ return colordict #we can ask this dict if the color already exists
+
+def importColors(colorlist):
+ """check if colors exists an import"""
+ colordict=getColorDict()
+ scribus.statusMessage("Defining new colors...")
+ scribus.progressTotal(len(colorlist))
+ i=0
+ for color in colorlist:
+ name=color[0]
+ c=color[1]
+ m=color[2]
+ y=color[3]
+ k=color[4]
+ while colordict.has_key(name):# check if color already exists - then add PREFIX to name
+ name = PREFIX+name
+
+ scribus.defineColor(name, c, m, y, k)
+ i=i+1
+ scribus.progressSet(i)
+
+def main(argv):
+ """Main method for importing colors."""
+ if not scribus.haveDoc(): #do we have a doc?
+ scribus.messageBox("csv2color", "No document to import colors \n Please open one, first.")
+ sys.exit()
+ else:
+ filename=scribus.fileDialog("csv2color", "CSV files(*.csv *.CSV *.txt *.TXT)")
+ while os.path.isdir(filename):
+ filename=scribus.fileDialog("csv2color", "CSV files(*.csv *.CSV *.txt *.TXT)") #proper filename?
+ else:
+ try:
+ colorlist=getColorsFromCsv(filename)
+ messagestring = "You are going to import %i colors \n This may take a while" % len(colorlist)
+ answer = scribus.messageBox("csv2color", messagestring, button1=scribus.BUTTON_OK, button2=scribus.BUTTON_CANCEL)
+ if answer != scribus.BUTTON_OK:
+ sys.exit()
+ else:
+ importColors(colorlist)
+ scribus.docChanged(True)
+ scribus.messageBox("csv2color", "Colors imported! \n Thank you for using csv2color and Scribus!")
+ except:
+ scribus.messageBox("csv2color", "Could not import file!", icon=scribus.ICON_WARNING)
+ sys.exit()
+
+
+
+def main_wrapper(argv):
+ """The main_wrapper() function disables redrawing, sets a sensible generic
+ status bar message, and optionally sets up the progress bar. It then runs
+ the main() function. Once everything finishes it cleans up after the main()
+ function, making sure everything is sane before the script terminates."""
+ try:
+ #scribus.statusMessage("Running script...")
+ scribus.progressReset()
+ main(argv)
+ finally:
+ # Exit neatly even if the script terminated with an exception,
+ # so we leave the progress bar and status bar blank and make sure
+ # drawing is enabled.
+ if scribus.haveDoc():
+ scribus.setRedraw(True)
+ scribus.statusMessage("")
+ scribus.progressReset()
+
+# This code detects if the script is being run as a script, or imported as a module.
+# It only runs main() if being run as a script. This permits you to import your script
+# and control it manually for debugging.
+if __name__ == '__main__':
+ main_wrapper(sys.argv)
diff --git a/scribus/plugins/scriptplugin/scripts/importcsv2table.py b/scribus/plugins/scriptplugin/scripts/importcsv2table.py
new file mode 100644
index 0000000..5c628b1
--- /dev/null
+++ b/scribus/plugins/scriptplugin/scripts/importcsv2table.py
@@ -0,0 +1,208 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+ABOUT THIS SCRIPT:
+
+Import CSV data files as tables into Scribus
+
+1. Create any frame of any size on your page but positioned
+where you want the table to be located (upper left corner)
+
+2. Make sure it is selected
+
+3. Execute this script:
+
+You will be prompted first for the width of the left column in mm,
+then the right column in mm, then height of all cells, and finally
+for a csv filename
+
+4. The data from the csv file will be imported and a table of
+textboxes will be drawn on the page.
+
+LIMITATIONS:
+
+1. You are limited to two-column CSV data in your file.
+
+2. In Scribus versions 1.3.5svn, when the script ends, you cannot
+adjust text, colors, and line features for a group, whereas in 1.3.3.x,
+all of these can be done without ungrouping.
+
+HINTS:
+
+Postgresql:
+You can easily create a CSV file with a Postgresql database. From Postgresql,
+toggle unaligned output with the '\a' switch, then activate a comma as
+a separator with '\f ,' (without apostrophes). Send output to a file
+with '\o myfile.csv', then query your database.
+
+Sqlite3:
+You can use "sqlite3 -csv" in the command line or ".mode csv" in sqlite's
+interactive shell.
+
+############################
+
+LICENSE:
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+Author: Sebastian Stetter
+
+Modifications: Gregory Pittman
+
+please report bugs to: scribusscript@sebastianstetter.de
+"""
+
+from __future__ import division
+import sys
+
+try:
+ # Please do not use 'from scribus import *' . If you must use a 'from import',
+ # Do so _after_ the 'import scribus' and only import the names you need, such
+ # as commonly used constants.
+ import scribus
+except ImportError,err:
+ print "This Python script is written for the Scribus scripting interface."
+ print "It can only be run from within Scribus."
+ sys.exit(1)
+
+#########################
+# YOUR IMPORTS GO HERE #
+#########################
+import csv
+
+#get information about the area where the bale should be drawed
+def getPosition():
+ if scribus.selectionCount() == 1:
+ areaname = scribus.getSelectedObject()
+ position= scribus.getPosition(areaname)
+ vpos = position[1]
+ hpos = position[0]
+ scribus.deleteObject(areaname)
+ return vpos, hpos
+
+ else:
+ scribus.messageBox("csv2table", "please select ONE Object to mark the drawing area for the table")
+ sys.exit()
+
+#get the cvs data
+def getCSVdata():
+ """opens a csv file, reads it in and returns a 2 dimensional list with the data"""
+ csvfile = scribus.fileDialog("csv2table :: open file", "*.csv")
+ if csvfile != "":
+ try:
+ reader = csv.reader(file(csvfile))
+ datalist=[]
+ for row in reader:
+ rowlist=[]
+ for col in row:
+ rowlist.append(col)
+ datalist.append(rowlist)
+ return datalist
+ except Exception, e:
+ scribus.messageBox("csv2table", "Could not open file %s"%e)
+ else:
+ sys.exit
+
+def getDataInformation(list):
+ """takes a 2 dimensional list object and returns the numbers of rows and cols"""
+ datainfo = dict()
+ datainfo["rowcount"]=len(list)
+ datainfo["colcount"]= len(list[0])
+ return datainfo
+
+def cellsize(areainfo, datainfo):
+ """"takes the area and data info and calculates the prper cell size"""
+ csize=dict()
+ csize["v"]= areainfo["vsize"] / datainfo["rowcount"]
+ csize["h"]= areainfo["hsize"] / datainfo["colcount"]
+ return csize
+
+def main(argv):
+ """This is a documentation string. Write a description of what your code
+ does here. You should generally put documentation strings ("docstrings")
+ on all your Python functions."""
+ #########################
+ # YOUR CODE GOES HERE #
+ #########################
+ userdim=scribus.getUnit() #get unit and change it to mm
+ scribus.setUnit(scribus.UNIT_MILLIMETERS)
+ cellwidthleft = 0
+ cellwidthright = 0
+ cellHeight = 0
+ pos = getPosition()
+ while cellwidthleft <= 0:
+ cellwidthL = scribus.valueDialog('Left Cell Width','How wide (mm) do you wish left cells to be?','30.0')
+ cellwidthleft = float(cellwidthL)
+ while cellwidthright <= 0:
+ cellwidthR = scribus.valueDialog('Right Cell Width','How wide (mm) do you wish right cells to be?','30.0')
+ cellwidthright = float(cellwidthR)
+ while cellHeight <= 0:
+ cellheight = scribus.valueDialog('Cell Height','How tall (mm) do you wish cells to be?','10.0')
+ cellHeight = float(cellheight)
+ data = getCSVdata()
+ di= getDataInformation(data)
+ hposition=pos[1]
+ vposition=pos[0]
+
+ objectlist=[] # here we keep a record of all the created textboxes so we can group them later
+ i=0
+ scribus.progressTotal(len(data))
+ scribus.setRedraw(False)
+ for row in data:
+ c=0
+ for cell in row:
+ cell = cell.strip()
+ cellsize=cellwidthleft
+ if c == 1: cellsize=cellwidthright
+ textbox=scribus.createText(hposition, vposition, cellsize, cellHeight) #create a textbox
+ objectlist.append(textbox)
+ scribus.insertText(cell,0, textbox)#insert the text into the textbox
+ hposition=hposition+cellwidthleft #move the position for the next cell
+ c=1
+ vposition=vposition+cellHeight #set vertical position for next row
+ hposition=pos[1] #reset vertical position for next row
+ i=i+1
+ scribus.progressSet(i)
+
+ scribus.groupObjects(objectlist)
+ scribus.progressReset()
+ scribus.setUnit(userdim) # reset unit to previous value
+ scribus.docChanged(True)
+ scribus.statusMessage("Done")
+ scribus.setRedraw(True)
+
+def main_wrapper(argv):
+ """The main_wrapper() function disables redrawing, sets a sensible generic
+ status bar message, and optionally sets up the progress bar. It then runs
+ the main() function. Once everything finishes it cleans up after the main()
+ function, making sure everything is sane before the script terminates."""
+ try:
+ scribus.statusMessage("Importing .csv table...")
+ scribus.progressReset()
+ main(argv)
+ finally:
+ # Exit neatly even if the script terminated with an exception,
+ # so we leave the progress bar and status bar blank and make sure
+ # drawing is enabled.
+ if scribus.haveDoc():
+ scribus.setRedraw(True)
+ scribus.statusMessage("")
+ scribus.progressReset()
+
+# This code detects if the script is being run as a script, or imported as a module.
+# It only runs main() if being run as a script. This permits you to import your script
+# and control it manually for debugging.
+if __name__ == '__main__':
+ main_wrapper(sys.argv)