code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
#!/usr/bin/env python
import ConfigParser
import os
import sys
import time
from threading import Thread
from optparse import OptionParser
import subprocess
def getServers(sectionname) :
"""
Returns a list of hostnames for a given sectionname in the configuration file.
If the section was a group, we'll traverse the configuration further
"""
servers = []
if not config.has_section(sectionname): raise RuntimeError('Server or group ' + sectionname + ' not found in configuration')
# Checking if the configuration file has a 'host' section
if config.has_option(sectionname,'host'):
servers.append(config.get(sectionname,'host'))
# Checking if the configuration has a 'group' section
if (config.has_option(sectionname,'group')):
grouplist = config.get(sectionname,'group').split(',')
for i in grouplist :
servers+=getServers(i)
return servers
class FloepCommand(Thread) :
"""
This is our worker process
It's responsible for executing the command, and storing the results afterwards
"""
def __init__ (self,host,command,options) :
Thread.__init__(self)
self.host = host
self.command = command
self.options = options
def run(self) :
commandstring = self.options.command % {'host' : self.host, 'command' : self.command}
process = subprocess.Popen(commandstring,stderr=subprocess.STDOUT,stdout=subprocess.PIPE,shell=True).stdout
self.result = process.read()
def readConfiguration() :
global commandTemplate
global defaultGroup
config.read(os.path.dirname(sys.argv[0]) + '/floep.cfg')
config.read('floep.cfg')
if config.has_option('settings','commandTemplate'):
commandTemplate = config.get('settings','commandTemplate')
else:
commandTemplate = 'ssh %(host)s %(command)s'
if config.has_option('settings','defaultGroup'):
defaultGroup = config.get('settings','defaultGroup')
else:
defaultGroup = 'all'
def parseOptions() :
global commandTemplate
parser = OptionParser(
version="floep 0.1",
description="Executes a command on multiple hosts"
)
parser.disable_interspersed_args()
parser.add_option(
'-g','--group',
default=defaultGroup,
type="string",
help="Execute command on group",
dest="group")
parser.add_option(
'-q','--quiet',
action="store_false",
help="Display only server output",
dest="verbose",
default=True)
parser.add_option(
'-c','--commandTemplate',
default=commandTemplate,
dest="command",
help="The commandline to execute for each host")
options,args = parser.parse_args()
if options.verbose:
print "floep 0.1"
if not args :
parser.error('no command given')
command = " ".join(args)
return options,command
def runCommandOnServers(servers,command,options) :
threadlist = []
for server in servers :
current = FloepCommand(server,command,options)
threadlist.append(current)
current.start()
while threadlist :
for server in threadlist :
if not server.isAlive():
server.join()
if options.verbose:
print "Result from", server.host, ":"
print server.result,
if options.verbose:
print ""
threadlist.remove(server)
break
else :
time.sleep(0.010)
commandTemplate = ''
config = ConfigParser.RawConfigParser()
def main() :
readConfiguration()
options,command = parseOptions()
servers = getServers(options.group)
runCommandOnServers(servers,command,options)
if __name__ == "__main__" :
main()
| Python |
#!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests the text output of Google C++ Mocking Framework.
SYNOPSIS
gmock_output_test.py --build_dir=BUILD/DIR --gengolden
# where BUILD/DIR contains the built gmock_output_test_ file.
gmock_output_test.py --gengolden
gmock_output_test.py
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import re
import sys
import gmock_test_utils
# The flag for generating the golden file
GENGOLDEN_FLAG = '--gengolden'
PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_output_test_')
COMMAND = [PROGRAM_PATH, '--gtest_stack_trace_depth=0', '--gtest_print_time=0']
GOLDEN_NAME = 'gmock_output_test_golden.txt'
GOLDEN_PATH = os.path.join(gmock_test_utils.GetSourceDir(), GOLDEN_NAME)
def ToUnixLineEnding(s):
"""Changes all Windows/Mac line endings in s to UNIX line endings."""
return s.replace('\r\n', '\n').replace('\r', '\n')
def RemoveReportHeaderAndFooter(output):
"""Removes Google Test result report's header and footer from the output."""
output = re.sub(r'.*gtest_main.*\n', '', output)
output = re.sub(r'\[.*\d+ tests.*\n', '', output)
output = re.sub(r'\[.* test environment .*\n', '', output)
output = re.sub(r'\[=+\] \d+ tests .* ran.*', '', output)
output = re.sub(r'.* FAILED TESTS\n', '', output)
return output
def RemoveLocations(output):
"""Removes all file location info from a Google Test program's output.
Args:
output: the output of a Google Test program.
Returns:
output with all file location info (in the form of
'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or
'DIRECTORY\\FILE_NAME(LINE_NUMBER): ') replaced by
'FILE:#: '.
"""
return re.sub(r'.*[/\\](.+)(\:\d+|\(\d+\))\:', 'FILE:#:', output)
def NormalizeErrorMarker(output):
"""Normalizes the error marker, which is different on Windows vs on Linux."""
return re.sub(r' error: ', ' Failure\n', output)
def RemoveMemoryAddresses(output):
"""Removes memory addresses from the test output."""
return re.sub(r'@\w+', '@0x#', output)
def RemoveTestNamesOfLeakedMocks(output):
"""Removes the test names of leaked mock objects from the test output."""
return re.sub(r'\(used in test .+\) ', '', output)
def GetLeakyTests(output):
"""Returns a list of test names that leak mock objects."""
# findall() returns a list of all matches of the regex in output.
# For example, if '(used in test FooTest.Bar)' is in output, the
# list will contain 'FooTest.Bar'.
return re.findall(r'\(used in test (.+)\)', output)
def GetNormalizedOutputAndLeakyTests(output):
"""Normalizes the output of gmock_output_test_.
Args:
output: The test output.
Returns:
A tuple (the normalized test output, the list of test names that have
leaked mocks).
"""
output = ToUnixLineEnding(output)
output = RemoveReportHeaderAndFooter(output)
output = NormalizeErrorMarker(output)
output = RemoveLocations(output)
output = RemoveMemoryAddresses(output)
return (RemoveTestNamesOfLeakedMocks(output), GetLeakyTests(output))
def GetShellCommandOutput(cmd):
"""Runs a command in a sub-process, and returns its STDOUT in a string."""
return gmock_test_utils.Subprocess(cmd, capture_stderr=False).output
def GetNormalizedCommandOutputAndLeakyTests(cmd):
"""Runs a command and returns its normalized output and a list of leaky tests.
Args:
cmd: the shell command.
"""
# Disables exception pop-ups on Windows.
os.environ['GTEST_CATCH_EXCEPTIONS'] = '1'
return GetNormalizedOutputAndLeakyTests(GetShellCommandOutput(cmd))
class GMockOutputTest(gmock_test_utils.TestCase):
def testOutput(self):
(output, leaky_tests) = GetNormalizedCommandOutputAndLeakyTests(COMMAND)
golden_file = open(GOLDEN_PATH, 'rb')
golden = golden_file.read()
golden_file.close()
# The normalized output should match the golden file.
self.assertEquals(golden, output)
# The raw output should contain 2 leaked mock object errors for
# test GMockOutputTest.CatchesLeakedMocks.
self.assertEquals(['GMockOutputTest.CatchesLeakedMocks',
'GMockOutputTest.CatchesLeakedMocks'],
leaky_tests)
if __name__ == '__main__':
if sys.argv[1:] == [GENGOLDEN_FLAG]:
(output, _) = GetNormalizedCommandOutputAndLeakyTests(COMMAND)
golden_file = open(GOLDEN_PATH, 'wb')
golden_file.write(output)
golden_file.close()
else:
gmock_test_utils.Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2009, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests that leaked mock objects can be caught be Google Mock."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import gmock_test_utils
PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_leak_test_')
TEST_WITH_EXPECT_CALL = [PROGRAM_PATH, '--gtest_filter=*ExpectCall*']
TEST_WITH_ON_CALL = [PROGRAM_PATH, '--gtest_filter=*OnCall*']
TEST_MULTIPLE_LEAKS = [PROGRAM_PATH, '--gtest_filter=*MultipleLeaked*']
class GMockLeakTest(gmock_test_utils.TestCase):
def testCatchesLeakedMockByDefault(self):
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL).exit_code)
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(TEST_WITH_ON_CALL).exit_code)
def testDoesNotCatchLeakedMockWhenDisabled(self):
self.assertEquals(
0,
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
['--gmock_catch_leaked_mocks=0']).exit_code)
self.assertEquals(
0,
gmock_test_utils.Subprocess(TEST_WITH_ON_CALL +
['--gmock_catch_leaked_mocks=0']).exit_code)
def testCatchesLeakedMockWhenEnabled(self):
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
['--gmock_catch_leaked_mocks']).exit_code)
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(TEST_WITH_ON_CALL +
['--gmock_catch_leaked_mocks']).exit_code)
def testCatchesLeakedMockWhenEnabledWithExplictFlagValue(self):
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
['--gmock_catch_leaked_mocks=1']).exit_code)
def testCatchesMultipleLeakedMocks(self):
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(TEST_MULTIPLE_LEAKS +
['--gmock_catch_leaked_mocks']).exit_code)
if __name__ == '__main__':
gmock_test_utils.Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test utilities for Google C++ Mocking Framework."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import sys
# Determines path to gtest_test_utils and imports it.
SCRIPT_DIR = os.path.dirname(__file__) or '.'
# isdir resolves symbolic links.
gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../gtest/test')
if os.path.isdir(gtest_tests_util_dir):
GTEST_TESTS_UTIL_DIR = gtest_tests_util_dir
else:
GTEST_TESTS_UTIL_DIR = os.path.join(SCRIPT_DIR, '../../gtest/test')
sys.path.append(GTEST_TESTS_UTIL_DIR)
import gtest_test_utils # pylint: disable-msg=C6204
def GetSourceDir():
"""Returns the absolute path of the directory where the .py files are."""
return gtest_test_utils.GetSourceDir()
def GetTestExecutablePath(executable_name):
"""Returns the absolute path of the test binary given its name.
The function will print a message and abort the program if the resulting file
doesn't exist.
Args:
executable_name: name of the test binary that the test script runs.
Returns:
The absolute path of the test binary.
"""
return gtest_test_utils.GetTestExecutablePath(executable_name)
def GetExitStatus(exit_code):
"""Returns the argument to exit(), or -1 if exit() wasn't called.
Args:
exit_code: the result value of os.system(command).
"""
if os.name == 'nt':
# On Windows, os.WEXITSTATUS() doesn't work and os.system() returns
# the argument to exit() directly.
return exit_code
else:
# On Unix, os.WEXITSTATUS() must be used to extract the exit status
# from the result of os.system().
if os.WIFEXITED(exit_code):
return os.WEXITSTATUS(exit_code)
else:
return -1
# Suppresses the "Invalid const name" lint complaint
# pylint: disable-msg=C6409
# Exposes Subprocess from gtest_test_utils.
Subprocess = gtest_test_utils.Subprocess
# Exposes TestCase from gtest_test_utils.
TestCase = gtest_test_utils.TestCase
# pylint: enable-msg=C6409
def Main():
"""Runs the unit test."""
gtest_test_utils.Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2008, Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Runs the specified tests for Google Mock.
This script requires Python 2.3 or higher. To learn the usage, run it
with -h.
"""
__author__ = 'vladl@google.com (Vlad Losev)'
import os
import sys
SCRIPT_DIR = os.path.dirname(__file__) or '.'
# Path to the Google Test code this Google Mock will use. We assume the
# gtest/ directory is either a subdirectory (possibly via a symbolic link)
# of gmock/ or a sibling.
#
# isdir resolves symbolic links.
if os.path.isdir(os.path.join(SCRIPT_DIR, 'gtest/test')):
RUN_TESTS_UTIL_DIR = os.path.join(SCRIPT_DIR, 'gtest/test')
else:
RUN_TESTS_UTIL_DIR = os.path.join(SCRIPT_DIR, '../gtest/test')
sys.path.append(RUN_TESTS_UTIL_DIR)
import run_tests_util
def GetGmockBuildDir(injected_os, script_dir, config):
return injected_os.path.normpath(injected_os.path.join(script_dir,
'scons/build',
config,
'gmock/scons'))
def _Main():
"""Runs all tests for Google Mock."""
options, args = run_tests_util.ParseArgs('gtest')
test_runner = run_tests_util.TestRunner(
script_dir=SCRIPT_DIR,
injected_build_dir_finder=GetGmockBuildDir)
tests = test_runner.GetTestsToRun(args,
options.configurations,
options.built_configurations)
if not tests:
sys.exit(1) # Incorrect parameters given, abort execution.
sys.exit(test_runner.RunTests(tests[0], tests[1]))
if __name__ == '__main__':
_Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tool for uploading diffs from a version control system to the codereview app.
Usage summary: upload.py [options] [-- diff_options]
Diff options are passed to the diff command of the underlying system.
Supported version control systems:
Git
Mercurial
Subversion
It is important for Git/Mercurial users to specify a tree/node/branch to diff
against by using the '--rev' option.
"""
# This code is derived from appcfg.py in the App Engine SDK (open source),
# and from ASPN recipe #146306.
import cookielib
import getpass
import logging
import md5
import mimetypes
import optparse
import os
import re
import socket
import subprocess
import sys
import urllib
import urllib2
import urlparse
try:
import readline
except ImportError:
pass
# The logging verbosity:
# 0: Errors only.
# 1: Status messages.
# 2: Info logs.
# 3: Debug logs.
verbosity = 1
# Max size of patch or base file.
MAX_UPLOAD_SIZE = 900 * 1024
def GetEmail(prompt):
"""Prompts the user for their email address and returns it.
The last used email address is saved to a file and offered up as a suggestion
to the user. If the user presses enter without typing in anything the last
used email address is used. If the user enters a new address, it is saved
for next time we prompt.
"""
last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
last_email = ""
if os.path.exists(last_email_file_name):
try:
last_email_file = open(last_email_file_name, "r")
last_email = last_email_file.readline().strip("\n")
last_email_file.close()
prompt += " [%s]" % last_email
except IOError, e:
pass
email = raw_input(prompt + ": ").strip()
if email:
try:
last_email_file = open(last_email_file_name, "w")
last_email_file.write(email)
last_email_file.close()
except IOError, e:
pass
else:
email = last_email
return email
def StatusUpdate(msg):
"""Print a status message to stdout.
If 'verbosity' is greater than 0, print the message.
Args:
msg: The string to print.
"""
if verbosity > 0:
print msg
def ErrorExit(msg):
"""Print an error message to stderr and exit."""
print >>sys.stderr, msg
sys.exit(1)
class ClientLoginError(urllib2.HTTPError):
"""Raised to indicate there was an error authenticating with ClientLogin."""
def __init__(self, url, code, msg, headers, args):
urllib2.HTTPError.__init__(self, url, code, msg, headers, None)
self.args = args
self.reason = args["Error"]
class AbstractRpcServer(object):
"""Provides a common interface for a simple RPC server."""
def __init__(self, host, auth_function, host_override=None, extra_headers={},
save_cookies=False):
"""Creates a new HttpRpcServer.
Args:
host: The host to send requests to.
auth_function: A function that takes no arguments and returns an
(email, password) tuple when called. Will be called if authentication
is required.
host_override: The host header to send to the server (defaults to host).
extra_headers: A dict of extra headers to append to every request.
save_cookies: If True, save the authentication cookies to local disk.
If False, use an in-memory cookiejar instead. Subclasses must
implement this functionality. Defaults to False.
"""
self.host = host
self.host_override = host_override
self.auth_function = auth_function
self.authenticated = False
self.extra_headers = extra_headers
self.save_cookies = save_cookies
self.opener = self._GetOpener()
if self.host_override:
logging.info("Server: %s; Host: %s", self.host, self.host_override)
else:
logging.info("Server: %s", self.host)
def _GetOpener(self):
"""Returns an OpenerDirector for making HTTP requests.
Returns:
A urllib2.OpenerDirector object.
"""
raise NotImplementedError()
def _CreateRequest(self, url, data=None):
"""Creates a new urllib request."""
logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
req = urllib2.Request(url, data=data)
if self.host_override:
req.add_header("Host", self.host_override)
for key, value in self.extra_headers.iteritems():
req.add_header(key, value)
return req
def _GetAuthToken(self, email, password):
"""Uses ClientLogin to authenticate the user, returning an auth token.
Args:
email: The user's email address
password: The user's password
Raises:
ClientLoginError: If there was an error authenticating with ClientLogin.
HTTPError: If there was some other form of HTTP error.
Returns:
The authentication token returned by ClientLogin.
"""
account_type = "GOOGLE"
if self.host.endswith(".google.com"):
# Needed for use inside Google.
account_type = "HOSTED"
req = self._CreateRequest(
url="https://www.google.com/accounts/ClientLogin",
data=urllib.urlencode({
"Email": email,
"Passwd": password,
"service": "ah",
"source": "rietveld-codereview-upload",
"accountType": account_type,
}),
)
try:
response = self.opener.open(req)
response_body = response.read()
response_dict = dict(x.split("=")
for x in response_body.split("\n") if x)
return response_dict["Auth"]
except urllib2.HTTPError, e:
if e.code == 403:
body = e.read()
response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
raise ClientLoginError(req.get_full_url(), e.code, e.msg,
e.headers, response_dict)
else:
raise
def _GetAuthCookie(self, auth_token):
"""Fetches authentication cookies for an authentication token.
Args:
auth_token: The authentication token returned by ClientLogin.
Raises:
HTTPError: If there was an error fetching the authentication cookies.
"""
# This is a dummy value to allow us to identify when we're successful.
continue_location = "http://localhost/"
args = {"continue": continue_location, "auth": auth_token}
req = self._CreateRequest("http://%s/_ah/login?%s" %
(self.host, urllib.urlencode(args)))
try:
response = self.opener.open(req)
except urllib2.HTTPError, e:
response = e
if (response.code != 302 or
response.info()["location"] != continue_location):
raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg,
response.headers, response.fp)
self.authenticated = True
def _Authenticate(self):
"""Authenticates the user.
The authentication process works as follows:
1) We get a username and password from the user
2) We use ClientLogin to obtain an AUTH token for the user
(see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
3) We pass the auth token to /_ah/login on the server to obtain an
authentication cookie. If login was successful, it tries to redirect
us to the URL we provided.
If we attempt to access the upload API without first obtaining an
authentication cookie, it returns a 401 response and directs us to
authenticate ourselves with ClientLogin.
"""
for i in range(3):
credentials = self.auth_function()
try:
auth_token = self._GetAuthToken(credentials[0], credentials[1])
except ClientLoginError, e:
if e.reason == "BadAuthentication":
print >>sys.stderr, "Invalid username or password."
continue
if e.reason == "CaptchaRequired":
print >>sys.stderr, (
"Please go to\n"
"https://www.google.com/accounts/DisplayUnlockCaptcha\n"
"and verify you are a human. Then try again.")
break
if e.reason == "NotVerified":
print >>sys.stderr, "Account not verified."
break
if e.reason == "TermsNotAgreed":
print >>sys.stderr, "User has not agreed to TOS."
break
if e.reason == "AccountDeleted":
print >>sys.stderr, "The user account has been deleted."
break
if e.reason == "AccountDisabled":
print >>sys.stderr, "The user account has been disabled."
break
if e.reason == "ServiceDisabled":
print >>sys.stderr, ("The user's access to the service has been "
"disabled.")
break
if e.reason == "ServiceUnavailable":
print >>sys.stderr, "The service is not available; try again later."
break
raise
self._GetAuthCookie(auth_token)
return
def Send(self, request_path, payload=None,
content_type="application/octet-stream",
timeout=None,
**kwargs):
"""Sends an RPC and returns the response.
Args:
request_path: The path to send the request to, eg /api/appversion/create.
payload: The body of the request, or None to send an empty request.
content_type: The Content-Type header to use.
timeout: timeout in seconds; default None i.e. no timeout.
(Note: for large requests on OS X, the timeout doesn't work right.)
kwargs: Any keyword arguments are converted into query string parameters.
Returns:
The response body, as a string.
"""
# TODO: Don't require authentication. Let the server say
# whether it is necessary.
if not self.authenticated:
self._Authenticate()
old_timeout = socket.getdefaulttimeout()
socket.setdefaulttimeout(timeout)
try:
tries = 0
while True:
tries += 1
args = dict(kwargs)
url = "http://%s%s" % (self.host, request_path)
if args:
url += "?" + urllib.urlencode(args)
req = self._CreateRequest(url=url, data=payload)
req.add_header("Content-Type", content_type)
try:
f = self.opener.open(req)
response = f.read()
f.close()
return response
except urllib2.HTTPError, e:
if tries > 3:
raise
elif e.code == 401:
self._Authenticate()
## elif e.code >= 500 and e.code < 600:
## # Server Error - try again.
## continue
else:
raise
finally:
socket.setdefaulttimeout(old_timeout)
class HttpRpcServer(AbstractRpcServer):
"""Provides a simplified RPC-style interface for HTTP requests."""
def _Authenticate(self):
"""Save the cookie jar after authentication."""
super(HttpRpcServer, self)._Authenticate()
if self.save_cookies:
StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
self.cookie_jar.save()
def _GetOpener(self):
"""Returns an OpenerDirector that supports cookies and ignores redirects.
Returns:
A urllib2.OpenerDirector object.
"""
opener = urllib2.OpenerDirector()
opener.add_handler(urllib2.ProxyHandler())
opener.add_handler(urllib2.UnknownHandler())
opener.add_handler(urllib2.HTTPHandler())
opener.add_handler(urllib2.HTTPDefaultErrorHandler())
opener.add_handler(urllib2.HTTPSHandler())
opener.add_handler(urllib2.HTTPErrorProcessor())
if self.save_cookies:
self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies")
self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
if os.path.exists(self.cookie_file):
try:
self.cookie_jar.load()
self.authenticated = True
StatusUpdate("Loaded authentication cookies from %s" %
self.cookie_file)
except (cookielib.LoadError, IOError):
# Failed to load cookies - just ignore them.
pass
else:
# Create an empty cookie file with mode 600
fd = os.open(self.cookie_file, os.O_CREAT, 0600)
os.close(fd)
# Always chmod the cookie file
os.chmod(self.cookie_file, 0600)
else:
# Don't save cookies across runs of update.py.
self.cookie_jar = cookielib.CookieJar()
opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar))
return opener
parser = optparse.OptionParser(usage="%prog [options] [-- diff_options]")
parser.add_option("-y", "--assume_yes", action="store_true",
dest="assume_yes", default=False,
help="Assume that the answer to yes/no questions is 'yes'.")
# Logging
group = parser.add_option_group("Logging options")
group.add_option("-q", "--quiet", action="store_const", const=0,
dest="verbose", help="Print errors only.")
group.add_option("-v", "--verbose", action="store_const", const=2,
dest="verbose", default=1,
help="Print info level logs (default).")
group.add_option("--noisy", action="store_const", const=3,
dest="verbose", help="Print all logs.")
# Review server
group = parser.add_option_group("Review server options")
group.add_option("-s", "--server", action="store", dest="server",
default="codereview.appspot.com",
metavar="SERVER",
help=("The server to upload to. The format is host[:port]. "
"Defaults to 'codereview.appspot.com'."))
group.add_option("-e", "--email", action="store", dest="email",
metavar="EMAIL", default=None,
help="The username to use. Will prompt if omitted.")
group.add_option("-H", "--host", action="store", dest="host",
metavar="HOST", default=None,
help="Overrides the Host header sent with all RPCs.")
group.add_option("--no_cookies", action="store_false",
dest="save_cookies", default=True,
help="Do not save authentication cookies to local disk.")
# Issue
group = parser.add_option_group("Issue options")
group.add_option("-d", "--description", action="store", dest="description",
metavar="DESCRIPTION", default=None,
help="Optional description when creating an issue.")
group.add_option("-f", "--description_file", action="store",
dest="description_file", metavar="DESCRIPTION_FILE",
default=None,
help="Optional path of a file that contains "
"the description when creating an issue.")
group.add_option("-r", "--reviewers", action="store", dest="reviewers",
metavar="REVIEWERS", default=None,
help="Add reviewers (comma separated email addresses).")
group.add_option("--cc", action="store", dest="cc",
metavar="CC", default=None,
help="Add CC (comma separated email addresses).")
# Upload options
group = parser.add_option_group("Patch options")
group.add_option("-m", "--message", action="store", dest="message",
metavar="MESSAGE", default=None,
help="A message to identify the patch. "
"Will prompt if omitted.")
group.add_option("-i", "--issue", type="int", action="store",
metavar="ISSUE", default=None,
help="Issue number to which to add. Defaults to new issue.")
group.add_option("--download_base", action="store_true",
dest="download_base", default=False,
help="Base files will be downloaded by the server "
"(side-by-side diffs may not work on files with CRs).")
group.add_option("--rev", action="store", dest="revision",
metavar="REV", default=None,
help="Branch/tree/revision to diff against (used by DVCS).")
group.add_option("--send_mail", action="store_true",
dest="send_mail", default=False,
help="Send notification email to reviewers.")
def GetRpcServer(options):
"""Returns an instance of an AbstractRpcServer.
Returns:
A new AbstractRpcServer, on which RPC calls can be made.
"""
rpc_server_class = HttpRpcServer
def GetUserCredentials():
"""Prompts the user for a username and password."""
email = options.email
if email is None:
email = GetEmail("Email (login for uploading to %s)" % options.server)
password = getpass.getpass("Password for %s: " % email)
return (email, password)
# If this is the dev_appserver, use fake authentication.
host = (options.host or options.server).lower()
if host == "localhost" or host.startswith("localhost:"):
email = options.email
if email is None:
email = "test@example.com"
logging.info("Using debug user %s. Override with --email" % email)
server = rpc_server_class(
options.server,
lambda: (email, "password"),
host_override=options.host,
extra_headers={"Cookie":
'dev_appserver_login="%s:False"' % email},
save_cookies=options.save_cookies)
# Don't try to talk to ClientLogin.
server.authenticated = True
return server
return rpc_server_class(options.server, GetUserCredentials,
host_override=options.host,
save_cookies=options.save_cookies)
def EncodeMultipartFormData(fields, files):
"""Encode form fields for multipart/form-data.
Args:
fields: A sequence of (name, value) elements for regular form fields.
files: A sequence of (name, filename, value) elements for data to be
uploaded as files.
Returns:
(content_type, body) ready for httplib.HTTP instance.
Source:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
"""
BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-'
CRLF = '\r\n'
lines = []
for (key, value) in fields:
lines.append('--' + BOUNDARY)
lines.append('Content-Disposition: form-data; name="%s"' % key)
lines.append('')
lines.append(value)
for (key, filename, value) in files:
lines.append('--' + BOUNDARY)
lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' %
(key, filename))
lines.append('Content-Type: %s' % GetContentType(filename))
lines.append('')
lines.append(value)
lines.append('--' + BOUNDARY + '--')
lines.append('')
body = CRLF.join(lines)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
def GetContentType(filename):
"""Helper to guess the content-type from the filename."""
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
# Use a shell for subcommands on Windows to get a PATH search.
use_shell = sys.platform.startswith("win")
def RunShellWithReturnCode(command, print_output=False,
universal_newlines=True):
"""Executes a command and returns the output from stdout and the return code.
Args:
command: Command to execute.
print_output: If True, the output is printed to stdout.
If False, both stdout and stderr are ignored.
universal_newlines: Use universal_newlines flag (default: True).
Returns:
Tuple (output, return code)
"""
logging.info("Running %s", command)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=use_shell, universal_newlines=universal_newlines)
if print_output:
output_array = []
while True:
line = p.stdout.readline()
if not line:
break
print line.strip("\n")
output_array.append(line)
output = "".join(output_array)
else:
output = p.stdout.read()
p.wait()
errout = p.stderr.read()
if print_output and errout:
print >>sys.stderr, errout
p.stdout.close()
p.stderr.close()
return output, p.returncode
def RunShell(command, silent_ok=False, universal_newlines=True,
print_output=False):
data, retcode = RunShellWithReturnCode(command, print_output,
universal_newlines)
if retcode:
ErrorExit("Got error status from %s:\n%s" % (command, data))
if not silent_ok and not data:
ErrorExit("No output from %s" % command)
return data
class VersionControlSystem(object):
"""Abstract base class providing an interface to the VCS."""
def __init__(self, options):
"""Constructor.
Args:
options: Command line options.
"""
self.options = options
def GenerateDiff(self, args):
"""Return the current diff as a string.
Args:
args: Extra arguments to pass to the diff command.
"""
raise NotImplementedError(
"abstract method -- subclass %s must override" % self.__class__)
def GetUnknownFiles(self):
"""Return a list of files unknown to the VCS."""
raise NotImplementedError(
"abstract method -- subclass %s must override" % self.__class__)
def CheckForUnknownFiles(self):
"""Show an "are you sure?" prompt if there are unknown files."""
unknown_files = self.GetUnknownFiles()
if unknown_files:
print "The following files are not added to version control:"
for line in unknown_files:
print line
prompt = "Are you sure to continue?(y/N) "
answer = raw_input(prompt).strip()
if answer != "y":
ErrorExit("User aborted")
def GetBaseFile(self, filename):
"""Get the content of the upstream version of a file.
Returns:
A tuple (base_content, new_content, is_binary, status)
base_content: The contents of the base file.
new_content: For text files, this is empty. For binary files, this is
the contents of the new file, since the diff output won't contain
information to reconstruct the current file.
is_binary: True iff the file is binary.
status: The status of the file.
"""
raise NotImplementedError(
"abstract method -- subclass %s must override" % self.__class__)
def GetBaseFiles(self, diff):
"""Helper that calls GetBase file for each file in the patch.
Returns:
A dictionary that maps from filename to GetBaseFile's tuple. Filenames
are retrieved based on lines that start with "Index:" or
"Property changes on:".
"""
files = {}
for line in diff.splitlines(True):
if line.startswith('Index:') or line.startswith('Property changes on:'):
unused, filename = line.split(':', 1)
# On Windows if a file has property changes its filename uses '\'
# instead of '/'.
filename = filename.strip().replace('\\', '/')
files[filename] = self.GetBaseFile(filename)
return files
def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options,
files):
"""Uploads the base files (and if necessary, the current ones as well)."""
def UploadFile(filename, file_id, content, is_binary, status, is_base):
"""Uploads a file to the server."""
file_too_large = False
if is_base:
type = "base"
else:
type = "current"
if len(content) > MAX_UPLOAD_SIZE:
print ("Not uploading the %s file for %s because it's too large." %
(type, filename))
file_too_large = True
content = ""
checksum = md5.new(content).hexdigest()
if options.verbose > 0 and not file_too_large:
print "Uploading %s file for %s" % (type, filename)
url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id)
form_fields = [("filename", filename),
("status", status),
("checksum", checksum),
("is_binary", str(is_binary)),
("is_current", str(not is_base)),
]
if file_too_large:
form_fields.append(("file_too_large", "1"))
if options.email:
form_fields.append(("user", options.email))
ctype, body = EncodeMultipartFormData(form_fields,
[("data", filename, content)])
response_body = rpc_server.Send(url, body,
content_type=ctype)
if not response_body.startswith("OK"):
StatusUpdate(" --> %s" % response_body)
sys.exit(1)
patches = dict()
[patches.setdefault(v, k) for k, v in patch_list]
for filename in patches.keys():
base_content, new_content, is_binary, status = files[filename]
file_id_str = patches.get(filename)
if file_id_str.find("nobase") != -1:
base_content = None
file_id_str = file_id_str[file_id_str.rfind("_") + 1:]
file_id = int(file_id_str)
if base_content != None:
UploadFile(filename, file_id, base_content, is_binary, status, True)
if new_content != None:
UploadFile(filename, file_id, new_content, is_binary, status, False)
def IsImage(self, filename):
"""Returns true if the filename has an image extension."""
mimetype = mimetypes.guess_type(filename)[0]
if not mimetype:
return False
return mimetype.startswith("image/")
class SubversionVCS(VersionControlSystem):
"""Implementation of the VersionControlSystem interface for Subversion."""
def __init__(self, options):
super(SubversionVCS, self).__init__(options)
if self.options.revision:
match = re.match(r"(\d+)(:(\d+))?", self.options.revision)
if not match:
ErrorExit("Invalid Subversion revision %s." % self.options.revision)
self.rev_start = match.group(1)
self.rev_end = match.group(3)
else:
self.rev_start = self.rev_end = None
# Cache output from "svn list -r REVNO dirname".
# Keys: dirname, Values: 2-tuple (ouput for start rev and end rev).
self.svnls_cache = {}
# SVN base URL is required to fetch files deleted in an older revision.
# Result is cached to not guess it over and over again in GetBaseFile().
required = self.options.download_base or self.options.revision is not None
self.svn_base = self._GuessBase(required)
def GuessBase(self, required):
"""Wrapper for _GuessBase."""
return self.svn_base
def _GuessBase(self, required):
"""Returns the SVN base URL.
Args:
required: If true, exits if the url can't be guessed, otherwise None is
returned.
"""
info = RunShell(["svn", "info"])
for line in info.splitlines():
words = line.split()
if len(words) == 2 and words[0] == "URL:":
url = words[1]
scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
username, netloc = urllib.splituser(netloc)
if username:
logging.info("Removed username from base URL")
if netloc.endswith("svn.python.org"):
if netloc == "svn.python.org":
if path.startswith("/projects/"):
path = path[9:]
elif netloc != "pythondev@svn.python.org":
ErrorExit("Unrecognized Python URL: %s" % url)
base = "http://svn.python.org/view/*checkout*%s/" % path
logging.info("Guessed Python base = %s", base)
elif netloc.endswith("svn.collab.net"):
if path.startswith("/repos/"):
path = path[6:]
base = "http://svn.collab.net/viewvc/*checkout*%s/" % path
logging.info("Guessed CollabNet base = %s", base)
elif netloc.endswith(".googlecode.com"):
path = path + "/"
base = urlparse.urlunparse(("http", netloc, path, params,
query, fragment))
logging.info("Guessed Google Code base = %s", base)
else:
path = path + "/"
base = urlparse.urlunparse((scheme, netloc, path, params,
query, fragment))
logging.info("Guessed base = %s", base)
return base
if required:
ErrorExit("Can't find URL in output from svn info")
return None
def GenerateDiff(self, args):
cmd = ["svn", "diff"]
if self.options.revision:
cmd += ["-r", self.options.revision]
cmd.extend(args)
data = RunShell(cmd)
count = 0
for line in data.splitlines():
if line.startswith("Index:") or line.startswith("Property changes on:"):
count += 1
logging.info(line)
if not count:
ErrorExit("No valid patches found in output from svn diff")
return data
def _CollapseKeywords(self, content, keyword_str):
"""Collapses SVN keywords."""
# svn cat translates keywords but svn diff doesn't. As a result of this
# behavior patching.PatchChunks() fails with a chunk mismatch error.
# This part was originally written by the Review Board development team
# who had the same problem (http://reviews.review-board.org/r/276/).
# Mapping of keywords to known aliases
svn_keywords = {
# Standard keywords
'Date': ['Date', 'LastChangedDate'],
'Revision': ['Revision', 'LastChangedRevision', 'Rev'],
'Author': ['Author', 'LastChangedBy'],
'HeadURL': ['HeadURL', 'URL'],
'Id': ['Id'],
# Aliases
'LastChangedDate': ['LastChangedDate', 'Date'],
'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'],
'LastChangedBy': ['LastChangedBy', 'Author'],
'URL': ['URL', 'HeadURL'],
}
def repl(m):
if m.group(2):
return "$%s::%s$" % (m.group(1), " " * len(m.group(3)))
return "$%s$" % m.group(1)
keywords = [keyword
for name in keyword_str.split(" ")
for keyword in svn_keywords.get(name, [])]
return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content)
def GetUnknownFiles(self):
status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True)
unknown_files = []
for line in status.split("\n"):
if line and line[0] == "?":
unknown_files.append(line)
return unknown_files
def ReadFile(self, filename):
"""Returns the contents of a file."""
file = open(filename, 'rb')
result = ""
try:
result = file.read()
finally:
file.close()
return result
def GetStatus(self, filename):
"""Returns the status of a file."""
if not self.options.revision:
status = RunShell(["svn", "status", "--ignore-externals", filename])
if not status:
ErrorExit("svn status returned no output for %s" % filename)
status_lines = status.splitlines()
# If file is in a cl, the output will begin with
# "\n--- Changelist 'cl_name':\n". See
# http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt
if (len(status_lines) == 3 and
not status_lines[0] and
status_lines[1].startswith("--- Changelist")):
status = status_lines[2]
else:
status = status_lines[0]
# If we have a revision to diff against we need to run "svn list"
# for the old and the new revision and compare the results to get
# the correct status for a file.
else:
dirname, relfilename = os.path.split(filename)
if dirname not in self.svnls_cache:
cmd = ["svn", "list", "-r", self.rev_start, dirname or "."]
out, returncode = RunShellWithReturnCode(cmd)
if returncode:
ErrorExit("Failed to get status for %s." % filename)
old_files = out.splitlines()
args = ["svn", "list"]
if self.rev_end:
args += ["-r", self.rev_end]
cmd = args + [dirname or "."]
out, returncode = RunShellWithReturnCode(cmd)
if returncode:
ErrorExit("Failed to run command %s" % cmd)
self.svnls_cache[dirname] = (old_files, out.splitlines())
old_files, new_files = self.svnls_cache[dirname]
if relfilename in old_files and relfilename not in new_files:
status = "D "
elif relfilename in old_files and relfilename in new_files:
status = "M "
else:
status = "A "
return status
def GetBaseFile(self, filename):
status = self.GetStatus(filename)
base_content = None
new_content = None
# If a file is copied its status will be "A +", which signifies
# "addition-with-history". See "svn st" for more information. We need to
# upload the original file or else diff parsing will fail if the file was
# edited.
if status[0] == "A" and status[3] != "+":
# We'll need to upload the new content if we're adding a binary file
# since diff's output won't contain it.
mimetype = RunShell(["svn", "propget", "svn:mime-type", filename],
silent_ok=True)
base_content = ""
is_binary = mimetype and not mimetype.startswith("text/")
if is_binary and self.IsImage(filename):
new_content = self.ReadFile(filename)
elif (status[0] in ("M", "D", "R") or
(status[0] == "A" and status[3] == "+") or # Copied file.
(status[0] == " " and status[1] == "M")): # Property change.
args = []
if self.options.revision:
url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
else:
# Don't change filename, it's needed later.
url = filename
args += ["-r", "BASE"]
cmd = ["svn"] + args + ["propget", "svn:mime-type", url]
mimetype, returncode = RunShellWithReturnCode(cmd)
if returncode:
# File does not exist in the requested revision.
# Reset mimetype, it contains an error message.
mimetype = ""
get_base = False
is_binary = mimetype and not mimetype.startswith("text/")
if status[0] == " ":
# Empty base content just to force an upload.
base_content = ""
elif is_binary:
if self.IsImage(filename):
get_base = True
if status[0] == "M":
if not self.rev_end:
new_content = self.ReadFile(filename)
else:
url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end)
new_content = RunShell(["svn", "cat", url],
universal_newlines=True, silent_ok=True)
else:
base_content = ""
else:
get_base = True
if get_base:
if is_binary:
universal_newlines = False
else:
universal_newlines = True
if self.rev_start:
# "svn cat -r REV delete_file.txt" doesn't work. cat requires
# the full URL with "@REV" appended instead of using "-r" option.
url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
base_content = RunShell(["svn", "cat", url],
universal_newlines=universal_newlines,
silent_ok=True)
else:
base_content = RunShell(["svn", "cat", filename],
universal_newlines=universal_newlines,
silent_ok=True)
if not is_binary:
args = []
if self.rev_start:
url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
else:
url = filename
args += ["-r", "BASE"]
cmd = ["svn"] + args + ["propget", "svn:keywords", url]
keywords, returncode = RunShellWithReturnCode(cmd)
if keywords and not returncode:
base_content = self._CollapseKeywords(base_content, keywords)
else:
StatusUpdate("svn status returned unexpected output: %s" % status)
sys.exit(1)
return base_content, new_content, is_binary, status[0:5]
class GitVCS(VersionControlSystem):
"""Implementation of the VersionControlSystem interface for Git."""
def __init__(self, options):
super(GitVCS, self).__init__(options)
# Map of filename -> hash of base file.
self.base_hashes = {}
def GenerateDiff(self, extra_args):
# This is more complicated than svn's GenerateDiff because we must convert
# the diff output to include an svn-style "Index:" line as well as record
# the hashes of the base files, so we can upload them along with our diff.
if self.options.revision:
extra_args = [self.options.revision] + extra_args
gitdiff = RunShell(["git", "diff", "--full-index"] + extra_args)
svndiff = []
filecount = 0
filename = None
for line in gitdiff.splitlines():
match = re.match(r"diff --git a/(.*) b/.*$", line)
if match:
filecount += 1
filename = match.group(1)
svndiff.append("Index: %s\n" % filename)
else:
# The "index" line in a git diff looks like this (long hashes elided):
# index 82c0d44..b2cee3f 100755
# We want to save the left hash, as that identifies the base file.
match = re.match(r"index (\w+)\.\.", line)
if match:
self.base_hashes[filename] = match.group(1)
svndiff.append(line + "\n")
if not filecount:
ErrorExit("No valid patches found in output from git diff")
return "".join(svndiff)
def GetUnknownFiles(self):
status = RunShell(["git", "ls-files", "--exclude-standard", "--others"],
silent_ok=True)
return status.splitlines()
def GetBaseFile(self, filename):
hash = self.base_hashes[filename]
base_content = None
new_content = None
is_binary = False
if hash == "0" * 40: # All-zero hash indicates no base file.
status = "A"
base_content = ""
else:
status = "M"
base_content, returncode = RunShellWithReturnCode(["git", "show", hash])
if returncode:
ErrorExit("Got error status from 'git show %s'" % hash)
return (base_content, new_content, is_binary, status)
class MercurialVCS(VersionControlSystem):
"""Implementation of the VersionControlSystem interface for Mercurial."""
def __init__(self, options, repo_dir):
super(MercurialVCS, self).__init__(options)
# Absolute path to repository (we can be in a subdir)
self.repo_dir = os.path.normpath(repo_dir)
# Compute the subdir
cwd = os.path.normpath(os.getcwd())
assert cwd.startswith(self.repo_dir)
self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/")
if self.options.revision:
self.base_rev = self.options.revision
else:
self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip()
def _GetRelPath(self, filename):
"""Get relative path of a file according to the current directory,
given its logical path in the repo."""
assert filename.startswith(self.subdir), filename
return filename[len(self.subdir):].lstrip(r"\/")
def GenerateDiff(self, extra_args):
# If no file specified, restrict to the current subdir
extra_args = extra_args or ["."]
cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args
data = RunShell(cmd, silent_ok=True)
svndiff = []
filecount = 0
for line in data.splitlines():
m = re.match("diff --git a/(\S+) b/(\S+)", line)
if m:
# Modify line to make it look like as it comes from svn diff.
# With this modification no changes on the server side are required
# to make upload.py work with Mercurial repos.
# NOTE: for proper handling of moved/copied files, we have to use
# the second filename.
filename = m.group(2)
svndiff.append("Index: %s" % filename)
svndiff.append("=" * 67)
filecount += 1
logging.info(line)
else:
svndiff.append(line)
if not filecount:
ErrorExit("No valid patches found in output from hg diff")
return "\n".join(svndiff) + "\n"
def GetUnknownFiles(self):
"""Return a list of files unknown to the VCS."""
args = []
status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."],
silent_ok=True)
unknown_files = []
for line in status.splitlines():
st, fn = line.split(" ", 1)
if st == "?":
unknown_files.append(fn)
return unknown_files
def GetBaseFile(self, filename):
# "hg status" and "hg cat" both take a path relative to the current subdir
# rather than to the repo root, but "hg diff" has given us the full path
# to the repo root.
base_content = ""
new_content = None
is_binary = False
oldrelpath = relpath = self._GetRelPath(filename)
# "hg status -C" returns two lines for moved/copied files, one otherwise
out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath])
out = out.splitlines()
# HACK: strip error message about missing file/directory if it isn't in
# the working copy
if out[0].startswith('%s: ' % relpath):
out = out[1:]
if len(out) > 1:
# Moved/copied => considered as modified, use old filename to
# retrieve base contents
oldrelpath = out[1].strip()
status = "M"
else:
status, _ = out[0].split(' ', 1)
if status != "A":
base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath],
silent_ok=True)
is_binary = "\0" in base_content # Mercurial's heuristic
if status != "R":
new_content = open(relpath, "rb").read()
is_binary = is_binary or "\0" in new_content
if is_binary and base_content:
# Fetch again without converting newlines
base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath],
silent_ok=True, universal_newlines=False)
if not is_binary or not self.IsImage(relpath):
new_content = None
return base_content, new_content, is_binary, status
# NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync.
def SplitPatch(data):
"""Splits a patch into separate pieces for each file.
Args:
data: A string containing the output of svn diff.
Returns:
A list of 2-tuple (filename, text) where text is the svn diff output
pertaining to filename.
"""
patches = []
filename = None
diff = []
for line in data.splitlines(True):
new_filename = None
if line.startswith('Index:'):
unused, new_filename = line.split(':', 1)
new_filename = new_filename.strip()
elif line.startswith('Property changes on:'):
unused, temp_filename = line.split(':', 1)
# When a file is modified, paths use '/' between directories, however
# when a property is modified '\' is used on Windows. Make them the same
# otherwise the file shows up twice.
temp_filename = temp_filename.strip().replace('\\', '/')
if temp_filename != filename:
# File has property changes but no modifications, create a new diff.
new_filename = temp_filename
if new_filename:
if filename and diff:
patches.append((filename, ''.join(diff)))
filename = new_filename
diff = [line]
continue
if diff is not None:
diff.append(line)
if filename and diff:
patches.append((filename, ''.join(diff)))
return patches
def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
"""Uploads a separate patch for each file in the diff output.
Returns a list of [patch_key, filename] for each file.
"""
patches = SplitPatch(data)
rv = []
for patch in patches:
if len(patch[1]) > MAX_UPLOAD_SIZE:
print ("Not uploading the patch for " + patch[0] +
" because the file is too large.")
continue
form_fields = [("filename", patch[0])]
if not options.download_base:
form_fields.append(("content_upload", "1"))
files = [("data", "data.diff", patch[1])]
ctype, body = EncodeMultipartFormData(form_fields, files)
url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
print "Uploading patch for " + patch[0]
response_body = rpc_server.Send(url, body, content_type=ctype)
lines = response_body.splitlines()
if not lines or lines[0] != "OK":
StatusUpdate(" --> %s" % response_body)
sys.exit(1)
rv.append([lines[1], patch[0]])
return rv
def GuessVCS(options):
"""Helper to guess the version control system.
This examines the current directory, guesses which VersionControlSystem
we're using, and returns an instance of the appropriate class. Exit with an
error if we can't figure it out.
Returns:
A VersionControlSystem instance. Exits if the VCS can't be guessed.
"""
# Mercurial has a command to get the base directory of a repository
# Try running it, but don't die if we don't have hg installed.
# NOTE: we try Mercurial first as it can sit on top of an SVN working copy.
try:
out, returncode = RunShellWithReturnCode(["hg", "root"])
if returncode == 0:
return MercurialVCS(options, out.strip())
except OSError, (errno, message):
if errno != 2: # ENOENT -- they don't have hg installed.
raise
# Subversion has a .svn in all working directories.
if os.path.isdir('.svn'):
logging.info("Guessed VCS = Subversion")
return SubversionVCS(options)
# Git has a command to test if you're in a git tree.
# Try running it, but don't die if we don't have git installed.
try:
out, returncode = RunShellWithReturnCode(["git", "rev-parse",
"--is-inside-work-tree"])
if returncode == 0:
return GitVCS(options)
except OSError, (errno, message):
if errno != 2: # ENOENT -- they don't have git installed.
raise
ErrorExit(("Could not guess version control system. "
"Are you in a working copy directory?"))
def RealMain(argv, data=None):
"""The real main function.
Args:
argv: Command line arguments.
data: Diff contents. If None (default) the diff is generated by
the VersionControlSystem implementation returned by GuessVCS().
Returns:
A 2-tuple (issue id, patchset id).
The patchset id is None if the base files are not uploaded by this
script (applies only to SVN checkouts).
"""
logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:"
"%(lineno)s %(message)s "))
os.environ['LC_ALL'] = 'C'
options, args = parser.parse_args(argv[1:])
global verbosity
verbosity = options.verbose
if verbosity >= 3:
logging.getLogger().setLevel(logging.DEBUG)
elif verbosity >= 2:
logging.getLogger().setLevel(logging.INFO)
vcs = GuessVCS(options)
if isinstance(vcs, SubversionVCS):
# base field is only allowed for Subversion.
# Note: Fetching base files may become deprecated in future releases.
base = vcs.GuessBase(options.download_base)
else:
base = None
if not base and options.download_base:
options.download_base = True
logging.info("Enabled upload of base file")
if not options.assume_yes:
vcs.CheckForUnknownFiles()
if data is None:
data = vcs.GenerateDiff(args)
files = vcs.GetBaseFiles(data)
if verbosity >= 1:
print "Upload server:", options.server, "(change with -s/--server)"
if options.issue:
prompt = "Message describing this patch set: "
else:
prompt = "New issue subject: "
message = options.message or raw_input(prompt).strip()
if not message:
ErrorExit("A non-empty message is required")
rpc_server = GetRpcServer(options)
form_fields = [("subject", message)]
if base:
form_fields.append(("base", base))
if options.issue:
form_fields.append(("issue", str(options.issue)))
if options.email:
form_fields.append(("user", options.email))
if options.reviewers:
for reviewer in options.reviewers.split(','):
if "@" in reviewer and not reviewer.split("@")[1].count(".") == 1:
ErrorExit("Invalid email address: %s" % reviewer)
form_fields.append(("reviewers", options.reviewers))
if options.cc:
for cc in options.cc.split(','):
if "@" in cc and not cc.split("@")[1].count(".") == 1:
ErrorExit("Invalid email address: %s" % cc)
form_fields.append(("cc", options.cc))
description = options.description
if options.description_file:
if options.description:
ErrorExit("Can't specify description and description_file")
file = open(options.description_file, 'r')
description = file.read()
file.close()
if description:
form_fields.append(("description", description))
# Send a hash of all the base file so the server can determine if a copy
# already exists in an earlier patchset.
base_hashes = ""
for file, info in files.iteritems():
if not info[0] is None:
checksum = md5.new(info[0]).hexdigest()
if base_hashes:
base_hashes += "|"
base_hashes += checksum + ":" + file
form_fields.append(("base_hashes", base_hashes))
# If we're uploading base files, don't send the email before the uploads, so
# that it contains the file status.
if options.send_mail and options.download_base:
form_fields.append(("send_mail", "1"))
if not options.download_base:
form_fields.append(("content_upload", "1"))
if len(data) > MAX_UPLOAD_SIZE:
print "Patch is large, so uploading file patches separately."
uploaded_diff_file = []
form_fields.append(("separate_patches", "1"))
else:
uploaded_diff_file = [("data", "data.diff", data)]
ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file)
response_body = rpc_server.Send("/upload", body, content_type=ctype)
patchset = None
if not options.download_base or not uploaded_diff_file:
lines = response_body.splitlines()
if len(lines) >= 2:
msg = lines[0]
patchset = lines[1].strip()
patches = [x.split(" ", 1) for x in lines[2:]]
else:
msg = response_body
else:
msg = response_body
StatusUpdate(msg)
if not response_body.startswith("Issue created.") and \
not response_body.startswith("Issue updated."):
sys.exit(0)
issue = msg[msg.rfind("/")+1:]
if not uploaded_diff_file:
result = UploadSeparatePatches(issue, rpc_server, patchset, data, options)
if not options.download_base:
patches = result
if not options.download_base:
vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files)
if options.send_mail:
rpc_server.Send("/" + issue + "/mail", payload="")
return issue, patchset
def main():
try:
RealMain(sys.argv)
except KeyboardInterrupt:
print
StatusUpdate("Interrupted.")
sys.exit(1)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
#
# Copyright 2008 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate Google Mock classes from base classes.
This program will read in a C++ source file and output the Google Mock
classes for the specified classes. If no class is specified, all
classes in the source file are emitted.
Usage:
gmock_class.py header-file.h [ClassName]...
Output is sent to stdout.
"""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
import os
import re
import sets
import sys
from cpp import ast
from cpp import utils
_VERSION = (1, 0, 1) # The version of this script.
# How many spaces to indent. Can set me with the INDENT environment variable.
_INDENT = 2
def _GenerateMethods(output_lines, source, class_node):
function_type = ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL
ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR
for node in class_node.body:
# We only care about virtual functions.
if (isinstance(node, ast.Function) and
node.modifiers & function_type and
not node.modifiers & ctor_or_dtor):
# Pick out all the elements we need from the original function.
const = ''
if node.modifiers & ast.FUNCTION_CONST:
const = 'CONST_'
return_type = 'void'
if node.return_type:
# Add modifiers like 'const'.
modifiers = ''
if node.return_type.modifiers:
modifiers = ' '.join(node.return_type.modifiers) + ' '
return_type = modifiers + node.return_type.name
if node.return_type.pointer:
return_type += '*'
if node.return_type.reference:
return_type += '&'
prefix = 'MOCK_%sMETHOD%d' % (const, len(node.parameters))
args = ''
if node.parameters:
# Get the full text of the parameters from the start
# of the first parameter to the end of the last parameter.
start = node.parameters[0].start
end = node.parameters[-1].end
# Remove // comments.
args_strings = re.sub(r'//.*', '', source[start:end])
# Condense multiple spaces and eliminate newlines putting the
# parameters together on a single line. Ensure there is a
# space in an argument which is split by a newline without
# intervening whitespace, e.g.: int\nBar
args = re.sub(' +', ' ', args_strings.replace('\n', ' '))
# Create the prototype.
indent = ' ' * _INDENT
line = ('%s%s(%s,\n%s%s(%s));' %
(indent, prefix, node.name, indent*3, return_type, args))
output_lines.append(line)
def _GenerateMocks(filename, source, ast_list, desired_class_names):
processed_class_names = sets.Set()
lines = []
for node in ast_list:
if (isinstance(node, ast.Class) and node.body and
# desired_class_names being None means that all classes are selected.
(not desired_class_names or node.name in desired_class_names)):
class_name = node.name
processed_class_names.add(class_name)
class_node = node
# Add namespace before the class.
if class_node.namespace:
lines.extend(['namespace %s {' % n for n in class_node.namespace]) # }
lines.append('')
# Add the class prolog.
lines.append('class Mock%s : public %s {' % (class_name, class_name)) # }
lines.append('%spublic:' % (' ' * (_INDENT // 2)))
# Add all the methods.
_GenerateMethods(lines, source, class_node)
# Close the class.
if lines:
# If there are no virtual methods, no need for a public label.
if len(lines) == 2:
del lines[-1]
# Only close the class if there really is a class.
lines.append('};')
lines.append('') # Add an extra newline.
# Close the namespace.
if class_node.namespace:
for i in range(len(class_node.namespace)-1, -1, -1):
lines.append('} // namespace %s' % class_node.namespace[i])
lines.append('') # Add an extra newline.
if desired_class_names:
missing_class_name_list = list(desired_class_names - processed_class_names)
if missing_class_name_list:
missing_class_name_list.sort()
sys.stderr.write('Class(es) not found in %s: %s\n' %
(filename, ', '.join(missing_class_name_list)))
elif not processed_class_names:
sys.stderr.write('No class found in %s\n' % filename)
return lines
def main(argv=sys.argv):
if len(argv) < 2:
sys.stderr.write('Google Mock Class Generator v%s\n\n' %
'.'.join(map(str, _VERSION)))
sys.stderr.write(__doc__)
return 1
global _INDENT
try:
_INDENT = int(os.environ['INDENT'])
except KeyError:
pass
except:
sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT'))
filename = argv[1]
desired_class_names = None # None means all classes in the source file.
if len(argv) >= 3:
desired_class_names = sets.Set(argv[2:])
source = utils.ReadFile(filename)
if source is None:
return 1
builder = ast.BuilderFromSource(source, filename)
try:
entire_ast = filter(None, builder.Generate())
except KeyboardInterrupt:
return
except:
# An error message was already printed since we couldn't parse.
pass
else:
lines = _GenerateMocks(filename, source, entire_ast, desired_class_names)
sys.stdout.write('\n'.join(lines))
if __name__ == '__main__':
main(sys.argv)
| Python |
#!/usr/bin/env python
#
# Copyright 2007 Neal Norwitz
# Portions Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generic utilities for C++ parsing."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
import sys
# Set to True to see the start/end token indices.
DEBUG = True
def ReadFile(filename, print_error=True):
"""Returns the contents of a file."""
try:
fp = open(filename)
try:
return fp.read()
finally:
fp.close()
except IOError:
if print_error:
print('Error reading %s: %s' % (filename, sys.exc_info()[1]))
return None
| Python |
#!/usr/bin/env python
#
# Copyright 2007 Neal Norwitz
# Portions Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""C++ keywords and helper utilities for determining keywords."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
try:
# Python 3.x
import builtins
except ImportError:
# Python 2.x
import __builtin__ as builtins
if not hasattr(builtins, 'set'):
# Nominal support for Python 2.3.
from sets import Set as set
TYPES = set('bool char int long short double float void wchar_t unsigned signed'.split())
TYPE_MODIFIERS = set('auto register const inline extern static virtual volatile mutable'.split())
ACCESS = set('public protected private friend'.split())
CASTS = set('static_cast const_cast dynamic_cast reinterpret_cast'.split())
OTHERS = set('true false asm class namespace using explicit this operator sizeof'.split())
OTHER_TYPES = set('new delete typedef struct union enum typeid typename template'.split())
CONTROL = set('case switch default if else return goto'.split())
EXCEPTION = set('try catch throw'.split())
LOOP = set('while do for break continue'.split())
ALL = TYPES | TYPE_MODIFIERS | ACCESS | CASTS | OTHERS | OTHER_TYPES | CONTROL | EXCEPTION | LOOP
def IsKeyword(token):
return token in ALL
def IsBuiltinType(token):
if token in ('virtual', 'inline'):
# These only apply to methods, they can't be types by themselves.
return False
return token in TYPES or token in TYPE_MODIFIERS
| Python |
#!/usr/bin/env python
#
# Copyright 2007 Neal Norwitz
# Portions Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tokenize C++ source code."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
try:
# Python 3.x
import builtins
except ImportError:
# Python 2.x
import __builtin__ as builtins
import sys
from cpp import utils
if not hasattr(builtins, 'set'):
# Nominal support for Python 2.3.
from sets import Set as set
# Add $ as a valid identifier char since so much code uses it.
_letters = 'abcdefghijklmnopqrstuvwxyz'
VALID_IDENTIFIER_CHARS = set(_letters + _letters.upper() + '_0123456789$')
HEX_DIGITS = set('0123456789abcdefABCDEF')
INT_OR_FLOAT_DIGITS = set('01234567890eE-+')
# C++0x string preffixes.
_STR_PREFIXES = set(('R', 'u8', 'u8R', 'u', 'uR', 'U', 'UR', 'L', 'LR'))
# Token types.
UNKNOWN = 'UNKNOWN'
SYNTAX = 'SYNTAX'
CONSTANT = 'CONSTANT'
NAME = 'NAME'
PREPROCESSOR = 'PREPROCESSOR'
# Where the token originated from. This can be used for backtracking.
# It is always set to WHENCE_STREAM in this code.
WHENCE_STREAM, WHENCE_QUEUE = range(2)
class Token(object):
"""Data container to represent a C++ token.
Tokens can be identifiers, syntax char(s), constants, or
pre-processor directives.
start contains the index of the first char of the token in the source
end contains the index of the last char of the token in the source
"""
def __init__(self, token_type, name, start, end):
self.token_type = token_type
self.name = name
self.start = start
self.end = end
self.whence = WHENCE_STREAM
def __str__(self):
if not utils.DEBUG:
return 'Token(%r)' % self.name
return 'Token(%r, %s, %s)' % (self.name, self.start, self.end)
__repr__ = __str__
def _GetString(source, start, i):
i = source.find('"', i+1)
while source[i-1] == '\\':
# Count the trailing backslashes.
backslash_count = 1
j = i - 2
while source[j] == '\\':
backslash_count += 1
j -= 1
# When trailing backslashes are even, they escape each other.
if (backslash_count % 2) == 0:
break
i = source.find('"', i+1)
return i + 1
def _GetChar(source, start, i):
# NOTE(nnorwitz): may not be quite correct, should be good enough.
i = source.find("'", i+1)
while source[i-1] == '\\':
# Need to special case '\\'.
if (i - 2) > start and source[i-2] == '\\':
break
i = source.find("'", i+1)
# Try to handle unterminated single quotes (in a #if 0 block).
if i < 0:
i = start
return i + 1
def GetTokens(source):
"""Returns a sequence of Tokens.
Args:
source: string of C++ source code.
Yields:
Token that represents the next token in the source.
"""
# Cache various valid character sets for speed.
valid_identifier_chars = VALID_IDENTIFIER_CHARS
hex_digits = HEX_DIGITS
int_or_float_digits = INT_OR_FLOAT_DIGITS
int_or_float_digits2 = int_or_float_digits | set('.')
# Only ignore errors while in a #if 0 block.
ignore_errors = False
count_ifs = 0
i = 0
end = len(source)
while i < end:
# Skip whitespace.
while i < end and source[i].isspace():
i += 1
if i >= end:
return
token_type = UNKNOWN
start = i
c = source[i]
if c.isalpha() or c == '_': # Find a string token.
token_type = NAME
while source[i] in valid_identifier_chars:
i += 1
# String and character constants can look like a name if
# they are something like L"".
if (source[i] == "'" and (i - start) == 1 and
source[start:i] in 'uUL'):
# u, U, and L are valid C++0x character preffixes.
token_type = CONSTANT
i = _GetChar(source, start, i)
elif source[i] == "'" and source[start:i] in _STR_PREFIXES:
token_type = CONSTANT
i = _GetString(source, start, i)
elif c == '/' and source[i+1] == '/': # Find // comments.
i = source.find('\n', i)
if i == -1: # Handle EOF.
i = end
continue
elif c == '/' and source[i+1] == '*': # Find /* comments. */
i = source.find('*/', i) + 2
continue
elif c in ':+-<>&|*=': # : or :: (plus other chars).
token_type = SYNTAX
i += 1
new_ch = source[i]
if new_ch == c:
i += 1
elif c == '-' and new_ch == '>':
i += 1
elif new_ch == '=':
i += 1
elif c in '()[]{}~!?^%;/.,': # Handle single char tokens.
token_type = SYNTAX
i += 1
if c == '.' and source[i].isdigit():
token_type = CONSTANT
i += 1
while source[i] in int_or_float_digits:
i += 1
# Handle float suffixes.
for suffix in ('l', 'f'):
if suffix == source[i:i+1].lower():
i += 1
break
elif c.isdigit(): # Find integer.
token_type = CONSTANT
if c == '0' and source[i+1] in 'xX':
# Handle hex digits.
i += 2
while source[i] in hex_digits:
i += 1
else:
while source[i] in int_or_float_digits2:
i += 1
# Handle integer (and float) suffixes.
for suffix in ('ull', 'll', 'ul', 'l', 'f', 'u'):
size = len(suffix)
if suffix == source[i:i+size].lower():
i += size
break
elif c == '"': # Find string.
token_type = CONSTANT
i = _GetString(source, start, i)
elif c == "'": # Find char.
token_type = CONSTANT
i = _GetChar(source, start, i)
elif c == '#': # Find pre-processor command.
token_type = PREPROCESSOR
got_if = source[i:i+3] == '#if' and source[i+3:i+4].isspace()
if got_if:
count_ifs += 1
elif source[i:i+6] == '#endif':
count_ifs -= 1
if count_ifs == 0:
ignore_errors = False
# TODO(nnorwitz): handle preprocessor statements (\ continuations).
while 1:
i1 = source.find('\n', i)
i2 = source.find('//', i)
i3 = source.find('/*', i)
i4 = source.find('"', i)
# NOTE(nnorwitz): doesn't handle comments in #define macros.
# Get the first important symbol (newline, comment, EOF/end).
i = min([x for x in (i1, i2, i3, i4, end) if x != -1])
# Handle #include "dir//foo.h" properly.
if source[i] == '"':
i = source.find('"', i+1) + 1
assert i > 0
continue
# Keep going if end of the line and the line ends with \.
if not (i == i1 and source[i-1] == '\\'):
if got_if:
condition = source[start+4:i].lstrip()
if (condition.startswith('0') or
condition.startswith('(0)')):
ignore_errors = True
break
i += 1
elif c == '\\': # Handle \ in code.
# This is different from the pre-processor \ handling.
i += 1
continue
elif ignore_errors:
# The tokenizer seems to be in pretty good shape. This
# raise is conditionally disabled so that bogus code
# in an #if 0 block can be handled. Since we will ignore
# it anyways, this is probably fine. So disable the
# exception and return the bogus char.
i += 1
else:
sys.stderr.write('Got invalid token in %s @ %d token:%s: %r\n' %
('?', i, c, source[i-10:i+10]))
raise RuntimeError('unexpected token')
if i <= 0:
print('Invalid index, exiting now.')
return
yield Token(token_type, source[start:i], start, i)
if __name__ == '__main__':
def main(argv):
"""Driver mostly for testing purposes."""
for filename in argv[1:]:
source = utils.ReadFile(filename)
if source is None:
continue
for token in GetTokens(source):
print('%-12s: %s' % (token.token_type, token.name))
# print('\r%6.2f%%' % (100.0 * index / token.end),)
sys.stdout.write('\n')
main(sys.argv)
| Python |
#!/usr/bin/env python
#
# Copyright 2007 Neal Norwitz
# Portions Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate an Abstract Syntax Tree (AST) for C++."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
# TODO:
# * Tokens should never be exported, need to convert to Nodes
# (return types, parameters, etc.)
# * Handle static class data for templatized classes
# * Handle casts (both C++ and C-style)
# * Handle conditions and loops (if/else, switch, for, while/do)
#
# TODO much, much later:
# * Handle #define
# * exceptions
try:
# Python 3.x
import builtins
except ImportError:
# Python 2.x
import __builtin__ as builtins
import sys
import traceback
from cpp import keywords
from cpp import tokenize
from cpp import utils
if not hasattr(builtins, 'reversed'):
# Support Python 2.3 and earlier.
def reversed(seq):
for i in range(len(seq)-1, -1, -1):
yield seq[i]
if not hasattr(builtins, 'next'):
# Support Python 2.5 and earlier.
def next(obj):
return obj.next()
VISIBILITY_PUBLIC, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE = range(3)
FUNCTION_NONE = 0x00
FUNCTION_CONST = 0x01
FUNCTION_VIRTUAL = 0x02
FUNCTION_PURE_VIRTUAL = 0x04
FUNCTION_CTOR = 0x08
FUNCTION_DTOR = 0x10
FUNCTION_ATTRIBUTE = 0x20
FUNCTION_UNKNOWN_ANNOTATION = 0x40
FUNCTION_THROW = 0x80
"""
These are currently unused. Should really handle these properly at some point.
TYPE_MODIFIER_INLINE = 0x010000
TYPE_MODIFIER_EXTERN = 0x020000
TYPE_MODIFIER_STATIC = 0x040000
TYPE_MODIFIER_CONST = 0x080000
TYPE_MODIFIER_REGISTER = 0x100000
TYPE_MODIFIER_VOLATILE = 0x200000
TYPE_MODIFIER_MUTABLE = 0x400000
TYPE_MODIFIER_MAP = {
'inline': TYPE_MODIFIER_INLINE,
'extern': TYPE_MODIFIER_EXTERN,
'static': TYPE_MODIFIER_STATIC,
'const': TYPE_MODIFIER_CONST,
'register': TYPE_MODIFIER_REGISTER,
'volatile': TYPE_MODIFIER_VOLATILE,
'mutable': TYPE_MODIFIER_MUTABLE,
}
"""
_INTERNAL_TOKEN = 'internal'
_NAMESPACE_POP = 'ns-pop'
# TODO(nnorwitz): use this as a singleton for templated_types, etc
# where we don't want to create a new empty dict each time. It is also const.
class _NullDict(object):
__contains__ = lambda self: False
keys = values = items = iterkeys = itervalues = iteritems = lambda self: ()
# TODO(nnorwitz): move AST nodes into a separate module.
class Node(object):
"""Base AST node."""
def __init__(self, start, end):
self.start = start
self.end = end
def IsDeclaration(self):
"""Returns bool if this node is a declaration."""
return False
def IsDefinition(self):
"""Returns bool if this node is a definition."""
return False
def IsExportable(self):
"""Returns bool if this node exportable from a header file."""
return False
def Requires(self, node):
"""Does this AST node require the definition of the node passed in?"""
return False
def XXX__str__(self):
return self._StringHelper(self.__class__.__name__, '')
def _StringHelper(self, name, suffix):
if not utils.DEBUG:
return '%s(%s)' % (name, suffix)
return '%s(%d, %d, %s)' % (name, self.start, self.end, suffix)
def __repr__(self):
return str(self)
class Define(Node):
def __init__(self, start, end, name, definition):
Node.__init__(self, start, end)
self.name = name
self.definition = definition
def __str__(self):
value = '%s %s' % (self.name, self.definition)
return self._StringHelper(self.__class__.__name__, value)
class Include(Node):
def __init__(self, start, end, filename, system):
Node.__init__(self, start, end)
self.filename = filename
self.system = system
def __str__(self):
fmt = '"%s"'
if self.system:
fmt = '<%s>'
return self._StringHelper(self.__class__.__name__, fmt % self.filename)
class Goto(Node):
def __init__(self, start, end, label):
Node.__init__(self, start, end)
self.label = label
def __str__(self):
return self._StringHelper(self.__class__.__name__, str(self.label))
class Expr(Node):
def __init__(self, start, end, expr):
Node.__init__(self, start, end)
self.expr = expr
def Requires(self, node):
# TODO(nnorwitz): impl.
return False
def __str__(self):
return self._StringHelper(self.__class__.__name__, str(self.expr))
class Return(Expr):
pass
class Delete(Expr):
pass
class Friend(Expr):
def __init__(self, start, end, expr, namespace):
Expr.__init__(self, start, end, expr)
self.namespace = namespace[:]
class Using(Node):
def __init__(self, start, end, names):
Node.__init__(self, start, end)
self.names = names
def __str__(self):
return self._StringHelper(self.__class__.__name__, str(self.names))
class Parameter(Node):
def __init__(self, start, end, name, parameter_type, default):
Node.__init__(self, start, end)
self.name = name
self.type = parameter_type
self.default = default
def Requires(self, node):
# TODO(nnorwitz): handle namespaces, etc.
return self.type.name == node.name
def __str__(self):
name = str(self.type)
suffix = '%s %s' % (name, self.name)
if self.default:
suffix += ' = ' + ''.join([d.name for d in self.default])
return self._StringHelper(self.__class__.__name__, suffix)
class _GenericDeclaration(Node):
def __init__(self, start, end, name, namespace):
Node.__init__(self, start, end)
self.name = name
self.namespace = namespace[:]
def FullName(self):
prefix = ''
if self.namespace and self.namespace[-1]:
prefix = '::'.join(self.namespace) + '::'
return prefix + self.name
def _TypeStringHelper(self, suffix):
if self.namespace:
names = [n or '<anonymous>' for n in self.namespace]
suffix += ' in ' + '::'.join(names)
return self._StringHelper(self.__class__.__name__, suffix)
# TODO(nnorwitz): merge with Parameter in some way?
class VariableDeclaration(_GenericDeclaration):
def __init__(self, start, end, name, var_type, initial_value, namespace):
_GenericDeclaration.__init__(self, start, end, name, namespace)
self.type = var_type
self.initial_value = initial_value
def Requires(self, node):
# TODO(nnorwitz): handle namespaces, etc.
return self.type.name == node.name
def ToString(self):
"""Return a string that tries to reconstitute the variable decl."""
suffix = '%s %s' % (self.type, self.name)
if self.initial_value:
suffix += ' = ' + self.initial_value
return suffix
def __str__(self):
return self._StringHelper(self.__class__.__name__, self.ToString())
class Typedef(_GenericDeclaration):
def __init__(self, start, end, name, alias, namespace):
_GenericDeclaration.__init__(self, start, end, name, namespace)
self.alias = alias
def IsDefinition(self):
return True
def IsExportable(self):
return True
def Requires(self, node):
# TODO(nnorwitz): handle namespaces, etc.
name = node.name
for token in self.alias:
if token is not None and name == token.name:
return True
return False
def __str__(self):
suffix = '%s, %s' % (self.name, self.alias)
return self._TypeStringHelper(suffix)
class _NestedType(_GenericDeclaration):
def __init__(self, start, end, name, fields, namespace):
_GenericDeclaration.__init__(self, start, end, name, namespace)
self.fields = fields
def IsDefinition(self):
return True
def IsExportable(self):
return True
def __str__(self):
suffix = '%s, {%s}' % (self.name, self.fields)
return self._TypeStringHelper(suffix)
class Union(_NestedType):
pass
class Enum(_NestedType):
pass
class Class(_GenericDeclaration):
def __init__(self, start, end, name, bases, templated_types, body, namespace):
_GenericDeclaration.__init__(self, start, end, name, namespace)
self.bases = bases
self.body = body
self.templated_types = templated_types
def IsDeclaration(self):
return self.bases is None and self.body is None
def IsDefinition(self):
return not self.IsDeclaration()
def IsExportable(self):
return not self.IsDeclaration()
def Requires(self, node):
# TODO(nnorwitz): handle namespaces, etc.
if self.bases:
for token_list in self.bases:
# TODO(nnorwitz): bases are tokens, do name comparision.
for token in token_list:
if token.name == node.name:
return True
# TODO(nnorwitz): search in body too.
return False
def __str__(self):
name = self.name
if self.templated_types:
name += '<%s>' % self.templated_types
suffix = '%s, %s, %s' % (name, self.bases, self.body)
return self._TypeStringHelper(suffix)
class Struct(Class):
pass
class Function(_GenericDeclaration):
def __init__(self, start, end, name, return_type, parameters,
modifiers, templated_types, body, namespace):
_GenericDeclaration.__init__(self, start, end, name, namespace)
converter = TypeConverter(namespace)
self.return_type = converter.CreateReturnType(return_type)
self.parameters = converter.ToParameters(parameters)
self.modifiers = modifiers
self.body = body
self.templated_types = templated_types
def IsDeclaration(self):
return self.body is None
def IsDefinition(self):
return self.body is not None
def IsExportable(self):
if self.return_type and 'static' in self.return_type.modifiers:
return False
return None not in self.namespace
def Requires(self, node):
if self.parameters:
# TODO(nnorwitz): parameters are tokens, do name comparision.
for p in self.parameters:
if p.name == node.name:
return True
# TODO(nnorwitz): search in body too.
return False
def __str__(self):
# TODO(nnorwitz): add templated_types.
suffix = ('%s %s(%s), 0x%02x, %s' %
(self.return_type, self.name, self.parameters,
self.modifiers, self.body))
return self._TypeStringHelper(suffix)
class Method(Function):
def __init__(self, start, end, name, in_class, return_type, parameters,
modifiers, templated_types, body, namespace):
Function.__init__(self, start, end, name, return_type, parameters,
modifiers, templated_types, body, namespace)
# TODO(nnorwitz): in_class could also be a namespace which can
# mess up finding functions properly.
self.in_class = in_class
class Type(_GenericDeclaration):
"""Type used for any variable (eg class, primitive, struct, etc)."""
def __init__(self, start, end, name, templated_types, modifiers,
reference, pointer, array):
"""
Args:
name: str name of main type
templated_types: [Class (Type?)] template type info between <>
modifiers: [str] type modifiers (keywords) eg, const, mutable, etc.
reference, pointer, array: bools
"""
_GenericDeclaration.__init__(self, start, end, name, [])
self.templated_types = templated_types
if not name and modifiers:
self.name = modifiers.pop()
self.modifiers = modifiers
self.reference = reference
self.pointer = pointer
self.array = array
def __str__(self):
prefix = ''
if self.modifiers:
prefix = ' '.join(self.modifiers) + ' '
name = str(self.name)
if self.templated_types:
name += '<%s>' % self.templated_types
suffix = prefix + name
if self.reference:
suffix += '&'
if self.pointer:
suffix += '*'
if self.array:
suffix += '[]'
return self._TypeStringHelper(suffix)
# By definition, Is* are always False. A Type can only exist in
# some sort of variable declaration, parameter, or return value.
def IsDeclaration(self):
return False
def IsDefinition(self):
return False
def IsExportable(self):
return False
class TypeConverter(object):
def __init__(self, namespace_stack):
self.namespace_stack = namespace_stack
def _GetTemplateEnd(self, tokens, start):
count = 1
end = start
while 1:
token = tokens[end]
end += 1
if token.name == '<':
count += 1
elif token.name == '>':
count -= 1
if count == 0:
break
return tokens[start:end-1], end
def ToType(self, tokens):
"""Convert [Token,...] to [Class(...), ] useful for base classes.
For example, code like class Foo : public Bar<x, y> { ... };
the "Bar<x, y>" portion gets converted to an AST.
Returns:
[Class(...), ...]
"""
result = []
name_tokens = []
reference = pointer = array = False
def AddType(templated_types):
# Partition tokens into name and modifier tokens.
names = []
modifiers = []
for t in name_tokens:
if keywords.IsKeyword(t.name):
modifiers.append(t.name)
else:
names.append(t.name)
name = ''.join(names)
result.append(Type(name_tokens[0].start, name_tokens[-1].end,
name, templated_types, modifiers,
reference, pointer, array))
del name_tokens[:]
i = 0
end = len(tokens)
while i < end:
token = tokens[i]
if token.name == '<':
new_tokens, new_end = self._GetTemplateEnd(tokens, i+1)
AddType(self.ToType(new_tokens))
# If there is a comma after the template, we need to consume
# that here otherwise it becomes part of the name.
i = new_end
reference = pointer = array = False
elif token.name == ',':
AddType([])
reference = pointer = array = False
elif token.name == '*':
pointer = True
elif token.name == '&':
reference = True
elif token.name == '[':
pointer = True
elif token.name == ']':
pass
else:
name_tokens.append(token)
i += 1
if name_tokens:
# No '<' in the tokens, just a simple name and no template.
AddType([])
return result
def DeclarationToParts(self, parts, needs_name_removed):
name = None
default = []
if needs_name_removed:
# Handle default (initial) values properly.
for i, t in enumerate(parts):
if t.name == '=':
default = parts[i+1:]
name = parts[i-1].name
if name == ']' and parts[i-2].name == '[':
name = parts[i-3].name
i -= 1
parts = parts[:i-1]
break
else:
if parts[-1].token_type == tokenize.NAME:
name = parts.pop().name
else:
# TODO(nnorwitz): this is a hack that happens for code like
# Register(Foo<T>); where it thinks this is a function call
# but it's actually a declaration.
name = '???'
modifiers = []
type_name = []
other_tokens = []
templated_types = []
i = 0
end = len(parts)
while i < end:
p = parts[i]
if keywords.IsKeyword(p.name):
modifiers.append(p.name)
elif p.name == '<':
templated_tokens, new_end = self._GetTemplateEnd(parts, i+1)
templated_types = self.ToType(templated_tokens)
i = new_end - 1
# Don't add a spurious :: to data members being initialized.
next_index = i + 1
if next_index < end and parts[next_index].name == '::':
i += 1
elif p.name in ('[', ']', '='):
# These are handled elsewhere.
other_tokens.append(p)
elif p.name not in ('*', '&', '>'):
# Ensure that names have a space between them.
if (type_name and type_name[-1].token_type == tokenize.NAME and
p.token_type == tokenize.NAME):
type_name.append(tokenize.Token(tokenize.SYNTAX, ' ', 0, 0))
type_name.append(p)
else:
other_tokens.append(p)
i += 1
type_name = ''.join([t.name for t in type_name])
return name, type_name, templated_types, modifiers, default, other_tokens
def ToParameters(self, tokens):
if not tokens:
return []
result = []
name = type_name = ''
type_modifiers = []
pointer = reference = array = False
first_token = None
default = []
def AddParameter():
if default:
del default[0] # Remove flag.
end = type_modifiers[-1].end
parts = self.DeclarationToParts(type_modifiers, True)
(name, type_name, templated_types, modifiers,
unused_default, unused_other_tokens) = parts
parameter_type = Type(first_token.start, first_token.end,
type_name, templated_types, modifiers,
reference, pointer, array)
p = Parameter(first_token.start, end, name,
parameter_type, default)
result.append(p)
template_count = 0
for s in tokens:
if not first_token:
first_token = s
if s.name == '<':
template_count += 1
elif s.name == '>':
template_count -= 1
if template_count > 0:
type_modifiers.append(s)
continue
if s.name == ',':
AddParameter()
name = type_name = ''
type_modifiers = []
pointer = reference = array = False
first_token = None
default = []
elif s.name == '*':
pointer = True
elif s.name == '&':
reference = True
elif s.name == '[':
array = True
elif s.name == ']':
pass # Just don't add to type_modifiers.
elif s.name == '=':
# Got a default value. Add any value (None) as a flag.
default.append(None)
elif default:
default.append(s)
else:
type_modifiers.append(s)
AddParameter()
return result
def CreateReturnType(self, return_type_seq):
if not return_type_seq:
return None
start = return_type_seq[0].start
end = return_type_seq[-1].end
_, name, templated_types, modifiers, default, other_tokens = \
self.DeclarationToParts(return_type_seq, False)
names = [n.name for n in other_tokens]
reference = '&' in names
pointer = '*' in names
array = '[' in names
return Type(start, end, name, templated_types, modifiers,
reference, pointer, array)
def GetTemplateIndices(self, names):
# names is a list of strings.
start = names.index('<')
end = len(names) - 1
while end > 0:
if names[end] == '>':
break
end -= 1
return start, end+1
class AstBuilder(object):
def __init__(self, token_stream, filename, in_class='', visibility=None,
namespace_stack=[]):
self.tokens = token_stream
self.filename = filename
# TODO(nnorwitz): use a better data structure (deque) for the queue.
# Switching directions of the "queue" improved perf by about 25%.
# Using a deque should be even better since we access from both sides.
self.token_queue = []
self.namespace_stack = namespace_stack[:]
self.in_class = in_class
if in_class is None:
self.in_class_name_only = None
else:
self.in_class_name_only = in_class.split('::')[-1]
self.visibility = visibility
self.in_function = False
self.current_token = None
# Keep the state whether we are currently handling a typedef or not.
self._handling_typedef = False
self.converter = TypeConverter(self.namespace_stack)
def HandleError(self, msg, token):
printable_queue = list(reversed(self.token_queue[-20:]))
sys.stderr.write('Got %s in %s @ %s %s\n' %
(msg, self.filename, token, printable_queue))
def Generate(self):
while 1:
token = self._GetNextToken()
if not token:
break
# Get the next token.
self.current_token = token
# Dispatch on the next token type.
if token.token_type == _INTERNAL_TOKEN:
if token.name == _NAMESPACE_POP:
self.namespace_stack.pop()
continue
try:
result = self._GenerateOne(token)
if result is not None:
yield result
except:
self.HandleError('exception', token)
raise
def _CreateVariable(self, pos_token, name, type_name, type_modifiers,
ref_pointer_name_seq, templated_types, value=None):
reference = '&' in ref_pointer_name_seq
pointer = '*' in ref_pointer_name_seq
array = '[' in ref_pointer_name_seq
var_type = Type(pos_token.start, pos_token.end, type_name,
templated_types, type_modifiers,
reference, pointer, array)
return VariableDeclaration(pos_token.start, pos_token.end,
name, var_type, value, self.namespace_stack)
def _GenerateOne(self, token):
if token.token_type == tokenize.NAME:
if (keywords.IsKeyword(token.name) and
not keywords.IsBuiltinType(token.name)):
method = getattr(self, 'handle_' + token.name)
return method()
elif token.name == self.in_class_name_only:
# The token name is the same as the class, must be a ctor if
# there is a paren. Otherwise, it's the return type.
# Peek ahead to get the next token to figure out which.
next = self._GetNextToken()
self._AddBackToken(next)
if next.token_type == tokenize.SYNTAX and next.name == '(':
return self._GetMethod([token], FUNCTION_CTOR, None, True)
# Fall through--handle like any other method.
# Handle data or function declaration/definition.
syntax = tokenize.SYNTAX
temp_tokens, last_token = \
self._GetVarTokensUpTo(syntax, '(', ';', '{', '[')
temp_tokens.insert(0, token)
if last_token.name == '(':
# If there is an assignment before the paren,
# this is an expression, not a method.
expr = bool([e for e in temp_tokens if e.name == '='])
if expr:
new_temp = self._GetTokensUpTo(tokenize.SYNTAX, ';')
temp_tokens.append(last_token)
temp_tokens.extend(new_temp)
last_token = tokenize.Token(tokenize.SYNTAX, ';', 0, 0)
if last_token.name == '[':
# Handle array, this isn't a method, unless it's an operator.
# TODO(nnorwitz): keep the size somewhere.
# unused_size = self._GetTokensUpTo(tokenize.SYNTAX, ']')
temp_tokens.append(last_token)
if temp_tokens[-2].name == 'operator':
temp_tokens.append(self._GetNextToken())
else:
temp_tokens2, last_token = \
self._GetVarTokensUpTo(tokenize.SYNTAX, ';')
temp_tokens.extend(temp_tokens2)
if last_token.name == ';':
# Handle data, this isn't a method.
parts = self.converter.DeclarationToParts(temp_tokens, True)
(name, type_name, templated_types, modifiers, default,
unused_other_tokens) = parts
t0 = temp_tokens[0]
names = [t.name for t in temp_tokens]
if templated_types:
start, end = self.converter.GetTemplateIndices(names)
names = names[:start] + names[end:]
default = ''.join([t.name for t in default])
return self._CreateVariable(t0, name, type_name, modifiers,
names, templated_types, default)
if last_token.name == '{':
self._AddBackTokens(temp_tokens[1:])
self._AddBackToken(last_token)
method_name = temp_tokens[0].name
method = getattr(self, 'handle_' + method_name, None)
if not method:
# Must be declaring a variable.
# TODO(nnorwitz): handle the declaration.
return None
return method()
return self._GetMethod(temp_tokens, 0, None, False)
elif token.token_type == tokenize.SYNTAX:
if token.name == '~' and self.in_class:
# Must be a dtor (probably not in method body).
token = self._GetNextToken()
# self.in_class can contain A::Name, but the dtor will only
# be Name. Make sure to compare against the right value.
if (token.token_type == tokenize.NAME and
token.name == self.in_class_name_only):
return self._GetMethod([token], FUNCTION_DTOR, None, True)
# TODO(nnorwitz): handle a lot more syntax.
elif token.token_type == tokenize.PREPROCESSOR:
# TODO(nnorwitz): handle more preprocessor directives.
# token starts with a #, so remove it and strip whitespace.
name = token.name[1:].lstrip()
if name.startswith('include'):
# Remove "include".
name = name[7:].strip()
assert name
# Handle #include \<newline> "header-on-second-line.h".
if name.startswith('\\'):
name = name[1:].strip()
assert name[0] in '<"', token
assert name[-1] in '>"', token
system = name[0] == '<'
filename = name[1:-1]
return Include(token.start, token.end, filename, system)
if name.startswith('define'):
# Remove "define".
name = name[6:].strip()
assert name
value = ''
for i, c in enumerate(name):
if c.isspace():
value = name[i:].lstrip()
name = name[:i]
break
return Define(token.start, token.end, name, value)
if name.startswith('if') and name[2:3].isspace():
condition = name[3:].strip()
if condition.startswith('0') or condition.startswith('(0)'):
self._SkipIf0Blocks()
return None
def _GetTokensUpTo(self, expected_token_type, expected_token):
return self._GetVarTokensUpTo(expected_token_type, expected_token)[0]
def _GetVarTokensUpTo(self, expected_token_type, *expected_tokens):
last_token = self._GetNextToken()
tokens = []
while (last_token.token_type != expected_token_type or
last_token.name not in expected_tokens):
tokens.append(last_token)
last_token = self._GetNextToken()
return tokens, last_token
# TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necesary.
def _IgnoreUpTo(self, token_type, token):
unused_tokens = self._GetTokensUpTo(token_type, token)
def _SkipIf0Blocks(self):
count = 1
while 1:
token = self._GetNextToken()
if token.token_type != tokenize.PREPROCESSOR:
continue
name = token.name[1:].lstrip()
if name.startswith('endif'):
count -= 1
if count == 0:
break
elif name.startswith('if'):
count += 1
def _GetMatchingChar(self, open_paren, close_paren, GetNextToken=None):
if GetNextToken is None:
GetNextToken = self._GetNextToken
# Assumes the current token is open_paren and we will consume
# and return up to the close_paren.
count = 1
token = GetNextToken()
while 1:
if token.token_type == tokenize.SYNTAX:
if token.name == open_paren:
count += 1
elif token.name == close_paren:
count -= 1
if count == 0:
break
yield token
token = GetNextToken()
yield token
def _GetParameters(self):
return self._GetMatchingChar('(', ')')
def GetScope(self):
return self._GetMatchingChar('{', '}')
def _GetNextToken(self):
if self.token_queue:
return self.token_queue.pop()
return next(self.tokens)
def _AddBackToken(self, token):
if token.whence == tokenize.WHENCE_STREAM:
token.whence = tokenize.WHENCE_QUEUE
self.token_queue.insert(0, token)
else:
assert token.whence == tokenize.WHENCE_QUEUE, token
self.token_queue.append(token)
def _AddBackTokens(self, tokens):
if tokens:
if tokens[-1].whence == tokenize.WHENCE_STREAM:
for token in tokens:
token.whence = tokenize.WHENCE_QUEUE
self.token_queue[:0] = reversed(tokens)
else:
assert tokens[-1].whence == tokenize.WHENCE_QUEUE, tokens
self.token_queue.extend(reversed(tokens))
def GetName(self, seq=None):
"""Returns ([tokens], next_token_info)."""
GetNextToken = self._GetNextToken
if seq is not None:
it = iter(seq)
GetNextToken = lambda: next(it)
next_token = GetNextToken()
tokens = []
last_token_was_name = False
while (next_token.token_type == tokenize.NAME or
(next_token.token_type == tokenize.SYNTAX and
next_token.name in ('::', '<'))):
# Two NAMEs in a row means the identifier should terminate.
# It's probably some sort of variable declaration.
if last_token_was_name and next_token.token_type == tokenize.NAME:
break
last_token_was_name = next_token.token_type == tokenize.NAME
tokens.append(next_token)
# Handle templated names.
if next_token.name == '<':
tokens.extend(self._GetMatchingChar('<', '>', GetNextToken))
last_token_was_name = True
next_token = GetNextToken()
return tokens, next_token
def GetMethod(self, modifiers, templated_types):
return_type_and_name = self._GetTokensUpTo(tokenize.SYNTAX, '(')
assert len(return_type_and_name) >= 1
return self._GetMethod(return_type_and_name, modifiers, templated_types,
False)
def _GetMethod(self, return_type_and_name, modifiers, templated_types,
get_paren):
template_portion = None
if get_paren:
token = self._GetNextToken()
assert token.token_type == tokenize.SYNTAX, token
if token.name == '<':
# Handle templatized dtors.
template_portion = [token]
template_portion.extend(self._GetMatchingChar('<', '>'))
token = self._GetNextToken()
assert token.token_type == tokenize.SYNTAX, token
assert token.name == '(', token
name = return_type_and_name.pop()
# Handle templatized ctors.
if name.name == '>':
index = 1
while return_type_and_name[index].name != '<':
index += 1
template_portion = return_type_and_name[index:] + [name]
del return_type_and_name[index:]
name = return_type_and_name.pop()
elif name.name == ']':
rt = return_type_and_name
assert rt[-1].name == '[', return_type_and_name
assert rt[-2].name == 'operator', return_type_and_name
name_seq = return_type_and_name[-2:]
del return_type_and_name[-2:]
name = tokenize.Token(tokenize.NAME, 'operator[]',
name_seq[0].start, name.end)
# Get the open paren so _GetParameters() below works.
unused_open_paren = self._GetNextToken()
# TODO(nnorwitz): store template_portion.
return_type = return_type_and_name
indices = name
if return_type:
indices = return_type[0]
# Force ctor for templatized ctors.
if name.name == self.in_class and not modifiers:
modifiers |= FUNCTION_CTOR
parameters = list(self._GetParameters())
del parameters[-1] # Remove trailing ')'.
# Handling operator() is especially weird.
if name.name == 'operator' and not parameters:
token = self._GetNextToken()
assert token.name == '(', token
parameters = list(self._GetParameters())
del parameters[-1] # Remove trailing ')'.
token = self._GetNextToken()
while token.token_type == tokenize.NAME:
modifier_token = token
token = self._GetNextToken()
if modifier_token.name == 'const':
modifiers |= FUNCTION_CONST
elif modifier_token.name == '__attribute__':
# TODO(nnorwitz): handle more __attribute__ details.
modifiers |= FUNCTION_ATTRIBUTE
assert token.name == '(', token
# Consume everything between the (parens).
unused_tokens = list(self._GetMatchingChar('(', ')'))
token = self._GetNextToken()
elif modifier_token.name == 'throw':
modifiers |= FUNCTION_THROW
assert token.name == '(', token
# Consume everything between the (parens).
unused_tokens = list(self._GetMatchingChar('(', ')'))
token = self._GetNextToken()
elif modifier_token.name == modifier_token.name.upper():
# HACK(nnorwitz): assume that all upper-case names
# are some macro we aren't expanding.
modifiers |= FUNCTION_UNKNOWN_ANNOTATION
else:
self.HandleError('unexpected token', modifier_token)
assert token.token_type == tokenize.SYNTAX, token
# Handle ctor initializers.
if token.name == ':':
# TODO(nnorwitz): anything else to handle for initializer list?
while token.name != ';' and token.name != '{':
token = self._GetNextToken()
# Handle pointer to functions that are really data but look
# like method declarations.
if token.name == '(':
if parameters[0].name == '*':
# name contains the return type.
name = parameters.pop()
# parameters contains the name of the data.
modifiers = [p.name for p in parameters]
# Already at the ( to open the parameter list.
function_parameters = list(self._GetMatchingChar('(', ')'))
del function_parameters[-1] # Remove trailing ')'.
# TODO(nnorwitz): store the function_parameters.
token = self._GetNextToken()
assert token.token_type == tokenize.SYNTAX, token
assert token.name == ';', token
return self._CreateVariable(indices, name.name, indices.name,
modifiers, '', None)
# At this point, we got something like:
# return_type (type::*name_)(params);
# This is a data member called name_ that is a function pointer.
# With this code: void (sq_type::*field_)(string&);
# We get: name=void return_type=[] parameters=sq_type ... field_
# TODO(nnorwitz): is return_type always empty?
# TODO(nnorwitz): this isn't even close to being correct.
# Just put in something so we don't crash and can move on.
real_name = parameters[-1]
modifiers = [p.name for p in self._GetParameters()]
del modifiers[-1] # Remove trailing ')'.
return self._CreateVariable(indices, real_name.name, indices.name,
modifiers, '', None)
if token.name == '{':
body = list(self.GetScope())
del body[-1] # Remove trailing '}'.
else:
body = None
if token.name == '=':
token = self._GetNextToken()
assert token.token_type == tokenize.CONSTANT, token
assert token.name == '0', token
modifiers |= FUNCTION_PURE_VIRTUAL
token = self._GetNextToken()
if token.name == '[':
# TODO(nnorwitz): store tokens and improve parsing.
# template <typename T, size_t N> char (&ASH(T (&seq)[N]))[N];
tokens = list(self._GetMatchingChar('[', ']'))
token = self._GetNextToken()
assert token.name == ';', (token, return_type_and_name, parameters)
# Looks like we got a method, not a function.
if len(return_type) > 2 and return_type[-1].name == '::':
return_type, in_class = \
self._GetReturnTypeAndClassName(return_type)
return Method(indices.start, indices.end, name.name, in_class,
return_type, parameters, modifiers, templated_types,
body, self.namespace_stack)
return Function(indices.start, indices.end, name.name, return_type,
parameters, modifiers, templated_types, body,
self.namespace_stack)
def _GetReturnTypeAndClassName(self, token_seq):
# Splitting the return type from the class name in a method
# can be tricky. For example, Return::Type::Is::Hard::To::Find().
# Where is the return type and where is the class name?
# The heuristic used is to pull the last name as the class name.
# This includes all the templated type info.
# TODO(nnorwitz): if there is only One name like in the
# example above, punt and assume the last bit is the class name.
# Ignore a :: prefix, if exists so we can find the first real name.
i = 0
if token_seq[0].name == '::':
i = 1
# Ignore a :: suffix, if exists.
end = len(token_seq) - 1
if token_seq[end-1].name == '::':
end -= 1
# Make a copy of the sequence so we can append a sentinel
# value. This is required for GetName will has to have some
# terminating condition beyond the last name.
seq_copy = token_seq[i:end]
seq_copy.append(tokenize.Token(tokenize.SYNTAX, '', 0, 0))
names = []
while i < end:
# Iterate through the sequence parsing out each name.
new_name, next = self.GetName(seq_copy[i:])
assert new_name, 'Got empty new_name, next=%s' % next
# We got a pointer or ref. Add it to the name.
if next and next.token_type == tokenize.SYNTAX:
new_name.append(next)
names.append(new_name)
i += len(new_name)
# Now that we have the names, it's time to undo what we did.
# Remove the sentinel value.
names[-1].pop()
# Flatten the token sequence for the return type.
return_type = [e for seq in names[:-1] for e in seq]
# The class name is the last name.
class_name = names[-1]
return return_type, class_name
def handle_bool(self):
pass
def handle_char(self):
pass
def handle_int(self):
pass
def handle_long(self):
pass
def handle_short(self):
pass
def handle_double(self):
pass
def handle_float(self):
pass
def handle_void(self):
pass
def handle_wchar_t(self):
pass
def handle_unsigned(self):
pass
def handle_signed(self):
pass
def _GetNestedType(self, ctor):
name = None
name_tokens, token = self.GetName()
if name_tokens:
name = ''.join([t.name for t in name_tokens])
# Handle forward declarations.
if token.token_type == tokenize.SYNTAX and token.name == ';':
return ctor(token.start, token.end, name, None,
self.namespace_stack)
if token.token_type == tokenize.NAME and self._handling_typedef:
self._AddBackToken(token)
return ctor(token.start, token.end, name, None,
self.namespace_stack)
# Must be the type declaration.
fields = list(self._GetMatchingChar('{', '}'))
del fields[-1] # Remove trailing '}'.
if token.token_type == tokenize.SYNTAX and token.name == '{':
next = self._GetNextToken()
new_type = ctor(token.start, token.end, name, fields,
self.namespace_stack)
# A name means this is an anonymous type and the name
# is the variable declaration.
if next.token_type != tokenize.NAME:
return new_type
name = new_type
token = next
# Must be variable declaration using the type prefixed with keyword.
assert token.token_type == tokenize.NAME, token
return self._CreateVariable(token, token.name, name, [], '', None)
def handle_struct(self):
# Special case the handling typedef/aliasing of structs here.
# It would be a pain to handle in the class code.
name_tokens, var_token = self.GetName()
if name_tokens:
next_token = self._GetNextToken()
is_syntax = (var_token.token_type == tokenize.SYNTAX and
var_token.name[0] in '*&')
is_variable = (var_token.token_type == tokenize.NAME and
next_token.name == ';')
variable = var_token
if is_syntax and not is_variable:
variable = next_token
temp = self._GetNextToken()
if temp.token_type == tokenize.SYNTAX and temp.name == '(':
# Handle methods declared to return a struct.
t0 = name_tokens[0]
struct = tokenize.Token(tokenize.NAME, 'struct',
t0.start-7, t0.start-2)
type_and_name = [struct]
type_and_name.extend(name_tokens)
type_and_name.extend((var_token, next_token))
return self._GetMethod(type_and_name, 0, None, False)
assert temp.name == ';', (temp, name_tokens, var_token)
if is_syntax or (is_variable and not self._handling_typedef):
modifiers = ['struct']
type_name = ''.join([t.name for t in name_tokens])
position = name_tokens[0]
return self._CreateVariable(position, variable.name, type_name,
modifiers, var_token.name, None)
name_tokens.extend((var_token, next_token))
self._AddBackTokens(name_tokens)
else:
self._AddBackToken(var_token)
return self._GetClass(Struct, VISIBILITY_PUBLIC, None)
def handle_union(self):
return self._GetNestedType(Union)
def handle_enum(self):
return self._GetNestedType(Enum)
def handle_auto(self):
# TODO(nnorwitz): warn about using auto? Probably not since it
# will be reclaimed and useful for C++0x.
pass
def handle_register(self):
pass
def handle_const(self):
pass
def handle_inline(self):
pass
def handle_extern(self):
pass
def handle_static(self):
pass
def handle_virtual(self):
# What follows must be a method.
token = token2 = self._GetNextToken()
if token.name == 'inline':
# HACK(nnorwitz): handle inline dtors by ignoring 'inline'.
token2 = self._GetNextToken()
if token2.token_type == tokenize.SYNTAX and token2.name == '~':
return self.GetMethod(FUNCTION_VIRTUAL + FUNCTION_DTOR, None)
assert token.token_type == tokenize.NAME or token.name == '::', token
return_type_and_name = self._GetTokensUpTo(tokenize.SYNTAX, '(')
return_type_and_name.insert(0, token)
if token2 is not token:
return_type_and_name.insert(1, token2)
return self._GetMethod(return_type_and_name, FUNCTION_VIRTUAL,
None, False)
def handle_volatile(self):
pass
def handle_mutable(self):
pass
def handle_public(self):
assert self.in_class
self.visibility = VISIBILITY_PUBLIC
def handle_protected(self):
assert self.in_class
self.visibility = VISIBILITY_PROTECTED
def handle_private(self):
assert self.in_class
self.visibility = VISIBILITY_PRIVATE
def handle_friend(self):
tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
assert tokens
t0 = tokens[0]
return Friend(t0.start, t0.end, tokens, self.namespace_stack)
def handle_static_cast(self):
pass
def handle_const_cast(self):
pass
def handle_dynamic_cast(self):
pass
def handle_reinterpret_cast(self):
pass
def handle_new(self):
pass
def handle_delete(self):
tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
assert tokens
return Delete(tokens[0].start, tokens[0].end, tokens)
def handle_typedef(self):
token = self._GetNextToken()
if (token.token_type == tokenize.NAME and
keywords.IsKeyword(token.name)):
# Token must be struct/enum/union/class.
method = getattr(self, 'handle_' + token.name)
self._handling_typedef = True
tokens = [method()]
self._handling_typedef = False
else:
tokens = [token]
# Get the remainder of the typedef up to the semi-colon.
tokens.extend(self._GetTokensUpTo(tokenize.SYNTAX, ';'))
# TODO(nnorwitz): clean all this up.
assert tokens
name = tokens.pop()
indices = name
if tokens:
indices = tokens[0]
if not indices:
indices = token
if name.name == ')':
# HACK(nnorwitz): Handle pointers to functions "properly".
if (len(tokens) >= 4 and
tokens[1].name == '(' and tokens[2].name == '*'):
tokens.append(name)
name = tokens[3]
elif name.name == ']':
# HACK(nnorwitz): Handle arrays properly.
if len(tokens) >= 2:
tokens.append(name)
name = tokens[1]
new_type = tokens
if tokens and isinstance(tokens[0], tokenize.Token):
new_type = self.converter.ToType(tokens)[0]
return Typedef(indices.start, indices.end, name.name,
new_type, self.namespace_stack)
def handle_typeid(self):
pass # Not needed yet.
def handle_typename(self):
pass # Not needed yet.
def _GetTemplatedTypes(self):
result = {}
tokens = list(self._GetMatchingChar('<', '>'))
len_tokens = len(tokens) - 1 # Ignore trailing '>'.
i = 0
while i < len_tokens:
key = tokens[i].name
i += 1
if keywords.IsKeyword(key) or key == ',':
continue
type_name = default = None
if i < len_tokens:
i += 1
if tokens[i-1].name == '=':
assert i < len_tokens, '%s %s' % (i, tokens)
default, unused_next_token = self.GetName(tokens[i:])
i += len(default)
else:
if tokens[i-1].name != ',':
# We got something like: Type variable.
# Re-adjust the key (variable) and type_name (Type).
key = tokens[i-1].name
type_name = tokens[i-2]
result[key] = (type_name, default)
return result
def handle_template(self):
token = self._GetNextToken()
assert token.token_type == tokenize.SYNTAX, token
assert token.name == '<', token
templated_types = self._GetTemplatedTypes()
# TODO(nnorwitz): for now, just ignore the template params.
token = self._GetNextToken()
if token.token_type == tokenize.NAME:
if token.name == 'class':
return self._GetClass(Class, VISIBILITY_PRIVATE, templated_types)
elif token.name == 'struct':
return self._GetClass(Struct, VISIBILITY_PUBLIC, templated_types)
elif token.name == 'friend':
return self.handle_friend()
self._AddBackToken(token)
tokens, last = self._GetVarTokensUpTo(tokenize.SYNTAX, '(', ';')
tokens.append(last)
self._AddBackTokens(tokens)
if last.name == '(':
return self.GetMethod(FUNCTION_NONE, templated_types)
# Must be a variable definition.
return None
def handle_true(self):
pass # Nothing to do.
def handle_false(self):
pass # Nothing to do.
def handle_asm(self):
pass # Not needed yet.
def handle_class(self):
return self._GetClass(Class, VISIBILITY_PRIVATE, None)
def _GetBases(self):
# Get base classes.
bases = []
while 1:
token = self._GetNextToken()
assert token.token_type == tokenize.NAME, token
# TODO(nnorwitz): store kind of inheritance...maybe.
if token.name not in ('public', 'protected', 'private'):
# If inheritance type is not specified, it is private.
# Just put the token back so we can form a name.
# TODO(nnorwitz): it would be good to warn about this.
self._AddBackToken(token)
else:
# Check for virtual inheritance.
token = self._GetNextToken()
if token.name != 'virtual':
self._AddBackToken(token)
else:
# TODO(nnorwitz): store that we got virtual for this base.
pass
base, next_token = self.GetName()
bases_ast = self.converter.ToType(base)
assert len(bases_ast) == 1, bases_ast
bases.append(bases_ast[0])
assert next_token.token_type == tokenize.SYNTAX, next_token
if next_token.name == '{':
token = next_token
break
# Support multiple inheritance.
assert next_token.name == ',', next_token
return bases, token
def _GetClass(self, class_type, visibility, templated_types):
class_name = None
class_token = self._GetNextToken()
if class_token.token_type != tokenize.NAME:
assert class_token.token_type == tokenize.SYNTAX, class_token
token = class_token
else:
self._AddBackToken(class_token)
name_tokens, token = self.GetName()
class_name = ''.join([t.name for t in name_tokens])
bases = None
if token.token_type == tokenize.SYNTAX:
if token.name == ';':
# Forward declaration.
return class_type(class_token.start, class_token.end,
class_name, None, templated_types, None,
self.namespace_stack)
if token.name in '*&':
# Inline forward declaration. Could be method or data.
name_token = self._GetNextToken()
next_token = self._GetNextToken()
if next_token.name == ';':
# Handle data
modifiers = ['class']
return self._CreateVariable(class_token, name_token.name,
class_name,
modifiers, token.name, None)
else:
# Assume this is a method.
tokens = (class_token, token, name_token, next_token)
self._AddBackTokens(tokens)
return self.GetMethod(FUNCTION_NONE, None)
if token.name == ':':
bases, token = self._GetBases()
body = None
if token.token_type == tokenize.SYNTAX and token.name == '{':
assert token.token_type == tokenize.SYNTAX, token
assert token.name == '{', token
ast = AstBuilder(self.GetScope(), self.filename, class_name,
visibility, self.namespace_stack)
body = list(ast.Generate())
if not self._handling_typedef:
token = self._GetNextToken()
if token.token_type != tokenize.NAME:
assert token.token_type == tokenize.SYNTAX, token
assert token.name == ';', token
else:
new_class = class_type(class_token.start, class_token.end,
class_name, bases, None,
body, self.namespace_stack)
modifiers = []
return self._CreateVariable(class_token,
token.name, new_class,
modifiers, token.name, None)
else:
if not self._handling_typedef:
self.HandleError('non-typedef token', token)
self._AddBackToken(token)
return class_type(class_token.start, class_token.end, class_name,
bases, None, body, self.namespace_stack)
def handle_namespace(self):
token = self._GetNextToken()
# Support anonymous namespaces.
name = None
if token.token_type == tokenize.NAME:
name = token.name
token = self._GetNextToken()
self.namespace_stack.append(name)
assert token.token_type == tokenize.SYNTAX, token
# Create an internal token that denotes when the namespace is complete.
internal_token = tokenize.Token(_INTERNAL_TOKEN, _NAMESPACE_POP,
None, None)
internal_token.whence = token.whence
if token.name == '=':
# TODO(nnorwitz): handle aliasing namespaces.
name, next_token = self.GetName()
assert next_token.name == ';', next_token
self._AddBackToken(internal_token)
else:
assert token.name == '{', token
tokens = list(self.GetScope())
# Replace the trailing } with the internal namespace pop token.
tokens[-1] = internal_token
# Handle namespace with nothing in it.
self._AddBackTokens(tokens)
return None
def handle_using(self):
tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
assert tokens
return Using(tokens[0].start, tokens[0].end, tokens)
def handle_explicit(self):
assert self.in_class
# Nothing much to do.
# TODO(nnorwitz): maybe verify the method name == class name.
# This must be a ctor.
return self.GetMethod(FUNCTION_CTOR, None)
def handle_this(self):
pass # Nothing to do.
def handle_operator(self):
# Pull off the next token(s?) and make that part of the method name.
pass
def handle_sizeof(self):
pass
def handle_case(self):
pass
def handle_switch(self):
pass
def handle_default(self):
token = self._GetNextToken()
assert token.token_type == tokenize.SYNTAX
assert token.name == ':'
def handle_if(self):
pass
def handle_else(self):
pass
def handle_return(self):
tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
if not tokens:
return Return(self.current_token.start, self.current_token.end, None)
return Return(tokens[0].start, tokens[0].end, tokens)
def handle_goto(self):
tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
assert len(tokens) == 1, str(tokens)
return Goto(tokens[0].start, tokens[0].end, tokens[0].name)
def handle_try(self):
pass # Not needed yet.
def handle_catch(self):
pass # Not needed yet.
def handle_throw(self):
pass # Not needed yet.
def handle_while(self):
pass
def handle_do(self):
pass
def handle_for(self):
pass
def handle_break(self):
self._IgnoreUpTo(tokenize.SYNTAX, ';')
def handle_continue(self):
self._IgnoreUpTo(tokenize.SYNTAX, ';')
def BuilderFromSource(source, filename):
"""Utility method that returns an AstBuilder from source code.
Args:
source: 'C++ source code'
filename: 'file1'
Returns:
AstBuilder
"""
return AstBuilder(tokenize.GetTokens(source), filename)
def PrintIndentifiers(filename, should_print):
"""Prints all identifiers for a C++ source file.
Args:
filename: 'file1'
should_print: predicate with signature: bool Function(token)
"""
source = utils.ReadFile(filename, False)
if source is None:
sys.stderr.write('Unable to find: %s\n' % filename)
return
#print('Processing %s' % actual_filename)
builder = BuilderFromSource(source, filename)
try:
for node in builder.Generate():
if should_print(node):
print(node.name)
except KeyboardInterrupt:
return
except:
pass
def PrintAllIndentifiers(filenames, should_print):
"""Prints all identifiers for each C++ source file in filenames.
Args:
filenames: ['file1', 'file2', ...]
should_print: predicate with signature: bool Function(token)
"""
for path in filenames:
PrintIndentifiers(path, should_print)
def main(argv):
for filename in argv[1:]:
source = utils.ReadFile(filename)
if source is None:
continue
print('Processing %s' % filename)
builder = BuilderFromSource(source, filename)
try:
entire_ast = filter(None, builder.Generate())
except KeyboardInterrupt:
return
except:
# Already printed a warning, print the traceback and continue.
traceback.print_exc()
else:
if utils.DEBUG:
for ast in entire_ast:
print(ast)
if __name__ == '__main__':
main(sys.argv)
| Python |
#!/usr/bin/env python
#
# Copyright 2009 Neal Norwitz All Rights Reserved.
# Portions Copyright 2009 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for gmock.scripts.generator.cpp.gmock_class."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
import os
import sys
import unittest
# Allow the cpp imports below to work when run as a standalone script.
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from cpp import ast
from cpp import gmock_class
class TestCase(unittest.TestCase):
"""Helper class that adds assert methods."""
def assertEqualIgnoreLeadingWhitespace(self, expected_lines, lines):
"""Specialized assert that ignores the indent level."""
stripped_lines = '\n'.join([s.lstrip() for s in lines.split('\n')])
self.assertEqual(expected_lines, stripped_lines)
class GenerateMethodsTest(TestCase):
def GenerateMethodSource(self, cpp_source):
"""Helper method to convert C++ source to gMock output source lines."""
method_source_lines = []
# <test> is a pseudo-filename, it is not read or written.
builder = ast.BuilderFromSource(cpp_source, '<test>')
ast_list = list(builder.Generate())
gmock_class._GenerateMethods(method_source_lines, cpp_source, ast_list[0])
return ''.join(method_source_lines)
def testStrangeNewlineInParameter(self):
source = """
class Foo {
public:
virtual void Bar(int
a) = 0;
};
"""
self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD1(Bar,\nvoid(int a));',
self.GenerateMethodSource(source))
def testDoubleSlashCommentsInParameterListAreRemoved(self):
source = """
class Foo {
public:
virtual void Bar(int a, // inline comments should be elided.
int b // inline comments should be elided.
) const = 0;
};
"""
self.assertEqualIgnoreLeadingWhitespace(
'MOCK_CONST_METHOD2(Bar,\nvoid(int a, int b));',
self.GenerateMethodSource(source))
def testCStyleCommentsInParameterListAreNotRemoved(self):
# NOTE(nnorwitz): I'm not sure if it's the best behavior to keep these
# comments. Also note that C style comments after the last parameter
# are still elided.
source = """
class Foo {
public:
virtual const string& Bar(int /* keeper */, int b);
};
"""
self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD2(Bar,\nconst string&(int /* keeper */, int b));',
self.GenerateMethodSource(source))
class GenerateMocksTest(TestCase):
def GenerateMocks(self, cpp_source):
"""Helper method to convert C++ source to complete gMock output source."""
# <test> is a pseudo-filename, it is not read or written.
filename = '<test>'
builder = ast.BuilderFromSource(cpp_source, filename)
ast_list = list(builder.Generate())
lines = gmock_class._GenerateMocks(filename, cpp_source, ast_list, None)
return '\n'.join(lines)
def testNamespaces(self):
source = """
namespace Foo {
namespace Bar { class Forward; }
namespace Baz {
class Test {
public:
virtual void Foo();
};
} // namespace Baz
} // namespace Foo
"""
expected = """\
namespace Foo {
namespace Baz {
class MockTest : public Test {
public:
MOCK_METHOD0(Foo,
void());
};
} // namespace Baz
} // namespace Foo
"""
self.assertEqualIgnoreLeadingWhitespace(
expected, self.GenerateMocks(source))
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
#
# Copyright 2008 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Driver for starting up Google Mock class generator."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
import os
import sys
if __name__ == '__main__':
# Add the directory of this script to the path so we can import gmock_class.
sys.path.append(os.path.dirname(__file__))
from cpp import gmock_class
# Fix the docstring in case they require the usage.
gmock_class.__doc__ = gmock_class.__doc__.replace('gmock_class.py', __file__)
gmock_class.main()
| Python |
#!/usr/bin/env python
#
# Copyright 2009, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""upload_gmock.py v0.1.0 -- uploads a Google Mock patch for review.
This simple wrapper passes all command line flags and
--cc=googlemock@googlegroups.com to upload.py.
USAGE: upload_gmock.py [options for upload.py]
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import sys
CC_FLAG = '--cc='
GMOCK_GROUP = 'googlemock@googlegroups.com'
def main():
# Finds the path to upload.py, assuming it is in the same directory
# as this file.
my_dir = os.path.dirname(os.path.abspath(__file__))
upload_py_path = os.path.join(my_dir, 'upload.py')
# Adds Google Mock discussion group to the cc line if it's not there
# already.
upload_py_argv = [upload_py_path]
found_cc_flag = False
for arg in sys.argv[1:]:
if arg.startswith(CC_FLAG):
found_cc_flag = True
cc_line = arg[len(CC_FLAG):]
cc_list = [addr for addr in cc_line.split(',') if addr]
if GMOCK_GROUP not in cc_list:
cc_list.append(GMOCK_GROUP)
upload_py_argv.append(CC_FLAG + ','.join(cc_list))
else:
upload_py_argv.append(arg)
if not found_cc_flag:
upload_py_argv.append(CC_FLAG + GMOCK_GROUP)
# Invokes upload.py with the modified command line flags.
os.execv(upload_py_path, upload_py_argv)
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Converts gcc errors in code using Google Mock to plain English."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import re
import sys
_VERSION = '1.0.3'
_COMMON_GMOCK_SYMBOLS = [
# Matchers
'_',
'A',
'AddressSatisfies',
'AllOf',
'An',
'AnyOf',
'ContainerEq',
'Contains',
'ContainsRegex',
'DoubleEq',
'ElementsAre',
'ElementsAreArray',
'EndsWith',
'Eq',
'Field',
'FloatEq',
'Ge',
'Gt',
'HasSubstr',
'IsInitializedProto',
'Le',
'Lt',
'MatcherCast',
'Matches',
'MatchesRegex',
'NanSensitiveDoubleEq',
'NanSensitiveFloatEq',
'Ne',
'Not',
'NotNull',
'Pointee',
'Property',
'Ref',
'ResultOf',
'SafeMatcherCast',
'StartsWith',
'StrCaseEq',
'StrCaseNe',
'StrEq',
'StrNe',
'Truly',
'TypedEq',
'Value',
# Actions
'Assign',
'ByRef',
'DeleteArg',
'DoAll',
'DoDefault',
'IgnoreResult',
'Invoke',
'InvokeArgument',
'InvokeWithoutArgs',
'Return',
'ReturnNew',
'ReturnNull',
'ReturnRef',
'SaveArg',
'SetArgReferee',
'SetArgumentPointee',
'SetArrayArgument',
'SetErrnoAndReturn',
'Throw',
'WithArg',
'WithArgs',
'WithoutArgs',
# Cardinalities
'AnyNumber',
'AtLeast',
'AtMost',
'Between',
'Exactly',
# Sequences
'InSequence',
'Sequence',
# Misc
'DefaultValue',
'Mock',
]
# Regex for matching source file path and line number in gcc's errors.
_FILE_LINE_RE = r'(?P<file>.*):(?P<line>\d+):\s+'
def _FindAllMatches(regex, s):
"""Generates all matches of regex in string s."""
r = re.compile(regex)
return r.finditer(s)
def _GenericDiagnoser(short_name, long_name, regex, diagnosis, msg):
"""Diagnoses the given disease by pattern matching.
Args:
short_name: Short name of the disease.
long_name: Long name of the disease.
regex: Regex for matching the symptoms.
diagnosis: Pattern for formatting the diagnosis.
msg: Gcc's error messages.
Yields:
Tuples of the form
(short name of disease, long name of disease, diagnosis).
"""
diagnosis = '%(file)s:%(line)s:' + diagnosis
for m in _FindAllMatches(regex, msg):
yield (short_name, long_name, diagnosis % m.groupdict())
def _NeedToReturnReferenceDiagnoser(msg):
"""Diagnoses the NRR disease, given the error messages by gcc."""
regex = (r'In member function \'testing::internal::ReturnAction<R>.*\n'
+ _FILE_LINE_RE + r'instantiated from here\n'
r'.*gmock-actions\.h.*error: creating array with negative size')
diagnosis = """
You are using an Return() action in a function that returns a reference.
Please use ReturnRef() instead."""
return _GenericDiagnoser('NRR', 'Need to Return Reference',
regex, diagnosis, msg)
def _NeedToReturnSomethingDiagnoser(msg):
"""Diagnoses the NRS disease, given the error messages by gcc."""
regex = (_FILE_LINE_RE +
r'(instantiated from here\n.'
r'*gmock.*actions\.h.*error: void value not ignored)'
r'|(error: control reaches end of non-void function)')
diagnosis = """
You are using an action that returns void, but it needs to return
*something*. Please tell it *what* to return. Perhaps you can use
the pattern DoAll(some_action, Return(some_value))?"""
return _GenericDiagnoser('NRS', 'Need to Return Something',
regex, diagnosis, msg)
def _NeedToReturnNothingDiagnoser(msg):
"""Diagnoses the NRN disease, given the error messages by gcc."""
regex = (_FILE_LINE_RE + r'instantiated from here\n'
r'.*gmock-actions\.h.*error: instantiation of '
r'\'testing::internal::ReturnAction<R>::Impl<F>::value_\' '
r'as type \'void\'')
diagnosis = """
You are using an action that returns *something*, but it needs to return
void. Please use a void-returning action instead.
All actions but the last in DoAll(...) must return void. Perhaps you need
to re-arrange the order of actions in a DoAll(), if you are using one?"""
return _GenericDiagnoser('NRN', 'Need to Return Nothing',
regex, diagnosis, msg)
def _IncompleteByReferenceArgumentDiagnoser(msg):
"""Diagnoses the IBRA disease, given the error messages by gcc."""
regex = (_FILE_LINE_RE + r'instantiated from here\n'
r'.*gtest-printers\.h.*error: invalid application of '
r'\'sizeof\' to incomplete type \'(?P<type>.*)\'')
diagnosis = """
In order to mock this function, Google Mock needs to see the definition
of type "%(type)s" - declaration alone is not enough. Either #include
the header that defines it, or change the argument to be passed
by pointer."""
return _GenericDiagnoser('IBRA', 'Incomplete By-Reference Argument Type',
regex, diagnosis, msg)
def _OverloadedFunctionMatcherDiagnoser(msg):
"""Diagnoses the OFM disease, given the error messages by gcc."""
regex = (_FILE_LINE_RE + r'error: no matching function for '
r'call to \'Truly\(<unresolved overloaded function type>\)')
diagnosis = """
The argument you gave to Truly() is an overloaded function. Please tell
gcc which overloaded version you want to use.
For example, if you want to use the version whose signature is
bool Foo(int n);
you should write
Truly(static_cast<bool (*)(int n)>(Foo))"""
return _GenericDiagnoser('OFM', 'Overloaded Function Matcher',
regex, diagnosis, msg)
def _OverloadedFunctionActionDiagnoser(msg):
"""Diagnoses the OFA disease, given the error messages by gcc."""
regex = (_FILE_LINE_RE + r'error: no matching function for call to \'Invoke\('
r'<unresolved overloaded function type>')
diagnosis = """
You are passing an overloaded function to Invoke(). Please tell gcc
which overloaded version you want to use.
For example, if you want to use the version whose signature is
bool MyFunction(int n, double x);
you should write something like
Invoke(static_cast<bool (*)(int n, double x)>(MyFunction))"""
return _GenericDiagnoser('OFA', 'Overloaded Function Action',
regex, diagnosis, msg)
def _OverloadedMethodActionDiagnoser1(msg):
"""Diagnoses the OMA disease, given the error messages by gcc."""
regex = (_FILE_LINE_RE + r'error: '
r'.*no matching function for call to \'Invoke\(.*, '
r'unresolved overloaded function type>')
diagnosis = """
The second argument you gave to Invoke() is an overloaded method. Please
tell gcc which overloaded version you want to use.
For example, if you want to use the version whose signature is
class Foo {
...
bool Bar(int n, double x);
};
you should write something like
Invoke(foo, static_cast<bool (Foo::*)(int n, double x)>(&Foo::Bar))"""
return _GenericDiagnoser('OMA', 'Overloaded Method Action',
regex, diagnosis, msg)
def _MockObjectPointerDiagnoser(msg):
"""Diagnoses the MOP disease, given the error messages by gcc."""
regex = (_FILE_LINE_RE + r'error: request for member '
r'\'gmock_(?P<method>.+)\' in \'(?P<mock_object>.+)\', '
r'which is of non-class type \'(.*::)*(?P<class_name>.+)\*\'')
diagnosis = """
The first argument to ON_CALL() and EXPECT_CALL() must be a mock *object*,
not a *pointer* to it. Please write '*(%(mock_object)s)' instead of
'%(mock_object)s' as your first argument.
For example, given the mock class:
class %(class_name)s : public ... {
...
MOCK_METHOD0(%(method)s, ...);
};
and the following mock instance:
%(class_name)s* mock_ptr = ...
you should use the EXPECT_CALL like this:
EXPECT_CALL(*mock_ptr, %(method)s(...));"""
return _GenericDiagnoser('MOP', 'Mock Object Pointer',
regex, diagnosis, msg)
def _OverloadedMethodActionDiagnoser2(msg):
"""Diagnoses the OMA disease, given the error messages by gcc."""
regex = (_FILE_LINE_RE + r'error: no matching function for '
r'call to \'Invoke\(.+, <unresolved overloaded function type>\)')
diagnosis = """
The second argument you gave to Invoke() is an overloaded method. Please
tell gcc which overloaded version you want to use.
For example, if you want to use the version whose signature is
class Foo {
...
bool Bar(int n, double x);
};
you should write something like
Invoke(foo, static_cast<bool (Foo::*)(int n, double x)>(&Foo::Bar))"""
return _GenericDiagnoser('OMA', 'Overloaded Method Action',
regex, diagnosis, msg)
def _NeedToUseSymbolDiagnoser(msg):
"""Diagnoses the NUS disease, given the error messages by gcc."""
regex = (_FILE_LINE_RE + r'error: \'(?P<symbol>.+)\' '
r'(was not declared in this scope|has not been declared)')
diagnosis = """
'%(symbol)s' is defined by Google Mock in the testing namespace.
Did you forget to write
using testing::%(symbol)s;
?"""
for m in _FindAllMatches(regex, msg):
symbol = m.groupdict()['symbol']
if symbol in _COMMON_GMOCK_SYMBOLS:
yield ('NUS', 'Need to Use Symbol', diagnosis % m.groupdict())
def _NeedToUseReturnNullDiagnoser(msg):
"""Diagnoses the NRNULL disease, given the error messages by gcc."""
regex = ('instantiated from \'testing::internal::ReturnAction<R>'
'::operator testing::Action<Func>\(\) const.*\n' +
_FILE_LINE_RE + r'instantiated from here\n'
r'.*error: no matching function for call to \'implicit_cast\('
r'long int&\)')
diagnosis = """
You are probably calling Return(NULL) and the compiler isn't sure how to turn
NULL into the right type. Use ReturnNull() instead.
Note: the line number may be off; please fix all instances of Return(NULL)."""
return _GenericDiagnoser('NRNULL', 'Need to use ReturnNull',
regex, diagnosis, msg)
_TTB_DIAGNOSIS = """
In a mock class template, types or typedefs defined in the base class
template are *not* automatically visible. This is how C++ works. Before
you can use a type or typedef named %(type)s defined in base class Base<T>, you
need to make it visible. One way to do it is:
typedef typename Base<T>::%(type)s %(type)s;"""
def _TypeInTemplatedBaseDiagnoser1(msg):
"""Diagnoses the TTB disease, given the error messages by gcc.
This version works when the type is used as the mock function's return
type.
"""
gcc_4_3_1_regex = (
r'In member function \'int .*\n' + _FILE_LINE_RE +
r'error: a function call cannot appear in a constant-expression')
gcc_4_4_0_regex = (
r'error: a function call cannot appear in a constant-expression'
+ _FILE_LINE_RE + r'error: template argument 1 is invalid\n')
diagnosis = _TTB_DIAGNOSIS % {'type': 'Foo'}
return (list(_GenericDiagnoser('TTB', 'Type in Template Base',
gcc_4_3_1_regex, diagnosis, msg)) +
list(_GenericDiagnoser('TTB', 'Type in Template Base',
gcc_4_4_0_regex, diagnosis, msg)))
def _TypeInTemplatedBaseDiagnoser2(msg):
"""Diagnoses the TTB disease, given the error messages by gcc.
This version works when the type is used as the mock function's sole
parameter type.
"""
regex = (_FILE_LINE_RE +
r'error: \'(?P<type>.+)\' was not declared in this scope\n'
r'.*error: template argument 1 is invalid\n')
return _GenericDiagnoser('TTB', 'Type in Template Base',
regex, _TTB_DIAGNOSIS, msg)
def _TypeInTemplatedBaseDiagnoser3(msg):
"""Diagnoses the TTB disease, given the error messages by gcc.
This version works when the type is used as a parameter of a mock
function that has multiple parameters.
"""
regex = (r'error: expected `;\' before \'::\' token\n'
+ _FILE_LINE_RE +
r'error: \'(?P<type>.+)\' was not declared in this scope\n'
r'.*error: template argument 1 is invalid\n'
r'.*error: \'.+\' was not declared in this scope')
return _GenericDiagnoser('TTB', 'Type in Template Base',
regex, _TTB_DIAGNOSIS, msg)
def _WrongMockMethodMacroDiagnoser(msg):
"""Diagnoses the WMM disease, given the error messages by gcc."""
regex = (_FILE_LINE_RE +
r'.*this_method_does_not_take_(?P<wrong_args>\d+)_argument.*\n'
r'.*\n'
r'.*candidates are.*FunctionMocker<[^>]+A(?P<args>\d+)\)>')
diagnosis = """
You are using MOCK_METHOD%(wrong_args)s to define a mock method that has
%(args)s arguments. Use MOCK_METHOD%(args)s (or MOCK_CONST_METHOD%(args)s,
MOCK_METHOD%(args)s_T, MOCK_CONST_METHOD%(args)s_T as appropriate) instead."""
return _GenericDiagnoser('WMM', 'Wrong MOCK_METHODn Macro',
regex, diagnosis, msg)
def _WrongParenPositionDiagnoser(msg):
"""Diagnoses the WPP disease, given the error messages by gcc."""
regex = (_FILE_LINE_RE +
r'error:.*testing::internal::MockSpec<.* has no member named \''
r'(?P<method>\w+)\'')
diagnosis = """
The closing parenthesis of ON_CALL or EXPECT_CALL should be *before*
".%(method)s". For example, you should write:
EXPECT_CALL(my_mock, Foo(_)).%(method)s(...);
instead of:
EXPECT_CALL(my_mock, Foo(_).%(method)s(...));"""
return _GenericDiagnoser('WPP', 'Wrong Parenthesis Position',
regex, diagnosis, msg)
_DIAGNOSERS = [
_IncompleteByReferenceArgumentDiagnoser,
_MockObjectPointerDiagnoser,
_NeedToReturnNothingDiagnoser,
_NeedToReturnReferenceDiagnoser,
_NeedToReturnSomethingDiagnoser,
_NeedToUseReturnNullDiagnoser,
_NeedToUseSymbolDiagnoser,
_OverloadedFunctionActionDiagnoser,
_OverloadedFunctionMatcherDiagnoser,
_OverloadedMethodActionDiagnoser1,
_OverloadedMethodActionDiagnoser2,
_TypeInTemplatedBaseDiagnoser1,
_TypeInTemplatedBaseDiagnoser2,
_TypeInTemplatedBaseDiagnoser3,
_WrongMockMethodMacroDiagnoser,
_WrongParenPositionDiagnoser,
]
def Diagnose(msg):
"""Generates all possible diagnoses given the gcc error message."""
diagnoses = []
for diagnoser in _DIAGNOSERS:
for diag in diagnoser(msg):
diagnosis = '[%s - %s]\n%s' % diag
if not diagnosis in diagnoses:
diagnoses.append(diagnosis)
return diagnoses
def main():
print ('Google Mock Doctor v%s - '
'diagnoses problems in code using Google Mock.' % _VERSION)
if sys.stdin.isatty():
print ('Please copy and paste the compiler errors here. Press c-D when '
'you are done:')
else:
print 'Waiting for compiler errors on stdin . . .'
msg = sys.stdin.read().strip()
diagnoses = Diagnose(msg)
count = len(diagnoses)
if not count:
print '\nGcc complained:'
print '8<------------------------------------------------------------'
print msg
print '------------------------------------------------------------>8'
print """
Uh-oh, I'm not smart enough to figure out what the problem is. :-(
However...
If you send your source code and gcc's error messages to
googlemock@googlegroups.com, you can be helped and I can get smarter --
win-win for us!"""
else:
print '------------------------------------------------------------'
print 'Your code appears to have the following',
if count > 1:
print '%s diseases:' % (count,)
else:
print 'disease:'
i = 0
for d in diagnoses:
i += 1
if count > 1:
print '\n#%s:' % (i,)
print d
print """
How did I do? If you think I'm wrong or unhelpful, please send your
source code and gcc's error messages to googlemock@googlegroups.com. Then
you can be helped and I can get smarter -- I promise I won't be upset!"""
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
#
# Copyright 2009, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""fuse_gmock_files.py v0.1.0
Fuses Google Mock and Google Test source code into two .h files and a .cc file.
SYNOPSIS
fuse_gmock_files.py [GMOCK_ROOT_DIR] OUTPUT_DIR
Scans GMOCK_ROOT_DIR for Google Mock and Google Test source
code, assuming Google Test is in the GMOCK_ROOT_DIR/gtest
sub-directory, and generates three files:
OUTPUT_DIR/gtest/gtest.h, OUTPUT_DIR/gmock/gmock.h, and
OUTPUT_DIR/gmock-gtest-all.cc. Then you can build your tests
by adding OUTPUT_DIR to the include search path and linking
with OUTPUT_DIR/gmock-gtest-all.cc. These three files contain
everything you need to use Google Mock. Hence you can
"install" Google Mock by copying them to wherever you want.
GMOCK_ROOT_DIR can be omitted and defaults to the parent
directory of the directory holding this script.
EXAMPLES
./fuse_gmock_files.py fused_gmock
./fuse_gmock_files.py path/to/unpacked/gmock fused_gmock
This tool is experimental. In particular, it assumes that there is no
conditional inclusion of Google Mock or Google Test headers. Please
report any problems to googlemock@googlegroups.com. You can read
http://code.google.com/p/googlemock/wiki/CookBook for more
information.
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import re
import sets
import sys
# We assume that this file is in the scripts/ directory in the Google
# Mock root directory.
DEFAULT_GMOCK_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
# We need to call into gtest/scripts/fuse_gtest_files.py.
sys.path.append(os.path.join(DEFAULT_GMOCK_ROOT_DIR, 'gtest/scripts'))
import fuse_gtest_files
gtest = fuse_gtest_files
# Regex for matching '#include <gmock/...>'.
INCLUDE_GMOCK_FILE_REGEX = re.compile(r'^\s*#\s*include\s*<(gmock/.+)>')
# Where to find the source seed files.
GMOCK_H_SEED = 'include/gmock/gmock.h'
GMOCK_ALL_CC_SEED = 'src/gmock-all.cc'
# Where to put the generated files.
GTEST_H_OUTPUT = 'gtest/gtest.h'
GMOCK_H_OUTPUT = 'gmock/gmock.h'
GMOCK_GTEST_ALL_CC_OUTPUT = 'gmock-gtest-all.cc'
def GetGTestRootDir(gmock_root):
"""Returns the root directory of Google Test."""
return os.path.join(gmock_root, 'gtest')
def ValidateGMockRootDir(gmock_root):
"""Makes sure gmock_root points to a valid gmock root directory.
The function aborts the program on failure.
"""
gtest.ValidateGTestRootDir(GetGTestRootDir(gmock_root))
gtest.VerifyFileExists(gmock_root, GMOCK_H_SEED)
gtest.VerifyFileExists(gmock_root, GMOCK_ALL_CC_SEED)
def ValidateOutputDir(output_dir):
"""Makes sure output_dir points to a valid output directory.
The function aborts the program on failure.
"""
gtest.VerifyOutputFile(output_dir, gtest.GTEST_H_OUTPUT)
gtest.VerifyOutputFile(output_dir, GMOCK_H_OUTPUT)
gtest.VerifyOutputFile(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT)
def FuseGMockH(gmock_root, output_dir):
"""Scans folder gmock_root to generate gmock/gmock.h in output_dir."""
output_file = file(os.path.join(output_dir, GMOCK_H_OUTPUT), 'w')
processed_files = sets.Set() # Holds all gmock headers we've processed.
def ProcessFile(gmock_header_path):
"""Processes the given gmock header file."""
# We don't process the same header twice.
if gmock_header_path in processed_files:
return
processed_files.add(gmock_header_path)
# Reads each line in the given gmock header.
for line in file(os.path.join(gmock_root, gmock_header_path), 'r'):
m = INCLUDE_GMOCK_FILE_REGEX.match(line)
if m:
# It's '#include <gmock/...>' - let's process it recursively.
ProcessFile('include/' + m.group(1))
else:
m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
if m:
# It's '#include <gtest/foo.h>'. We translate it to
# <gtest/gtest.h>, regardless of what foo is, since all
# gtest headers are fused into gtest/gtest.h.
# There is no need to #include gtest.h twice.
if not gtest.GTEST_H_SEED in processed_files:
processed_files.add(gtest.GTEST_H_SEED)
output_file.write('#include <%s>\n' % (gtest.GTEST_H_OUTPUT,))
else:
# Otherwise we copy the line unchanged to the output file.
output_file.write(line)
ProcessFile(GMOCK_H_SEED)
output_file.close()
def FuseGMockAllCcToFile(gmock_root, output_file):
"""Scans folder gmock_root to fuse gmock-all.cc into output_file."""
processed_files = sets.Set()
def ProcessFile(gmock_source_file):
"""Processes the given gmock source file."""
# We don't process the same #included file twice.
if gmock_source_file in processed_files:
return
processed_files.add(gmock_source_file)
# Reads each line in the given gmock source file.
for line in file(os.path.join(gmock_root, gmock_source_file), 'r'):
m = INCLUDE_GMOCK_FILE_REGEX.match(line)
if m:
# It's '#include <gmock/foo.h>'. We treat it as '#include
# <gmock/gmock.h>', as all other gmock headers are being fused
# into gmock.h and cannot be #included directly.
# There is no need to #include <gmock/gmock.h> more than once.
if not GMOCK_H_SEED in processed_files:
processed_files.add(GMOCK_H_SEED)
output_file.write('#include <%s>\n' % (GMOCK_H_OUTPUT,))
else:
m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
if m:
# It's '#include <gtest/...>'.
# There is no need to #include gtest.h as it has been
# #included by gtest-all.cc.
pass
else:
m = gtest.INCLUDE_SRC_FILE_REGEX.match(line)
if m:
# It's '#include "src/foo"' - let's process it recursively.
ProcessFile(m.group(1))
else:
# Otherwise we copy the line unchanged to the output file.
output_file.write(line)
ProcessFile(GMOCK_ALL_CC_SEED)
def FuseGMockGTestAllCc(gmock_root, output_dir):
"""Scans folder gmock_root to generate gmock-gtest-all.cc in output_dir."""
output_file = file(os.path.join(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT), 'w')
# First, fuse gtest-all.cc into gmock-gtest-all.cc.
gtest.FuseGTestAllCcToFile(GetGTestRootDir(gmock_root), output_file)
# Next, append fused gmock-all.cc to gmock-gtest-all.cc.
FuseGMockAllCcToFile(gmock_root, output_file)
output_file.close()
def FuseGMock(gmock_root, output_dir):
"""Fuses gtest.h, gmock.h, and gmock-gtest-all.h."""
ValidateGMockRootDir(gmock_root)
ValidateOutputDir(output_dir)
gtest.FuseGTestH(GetGTestRootDir(gmock_root), output_dir)
FuseGMockH(gmock_root, output_dir)
FuseGMockGTestAllCc(gmock_root, output_dir)
def main():
argc = len(sys.argv)
if argc == 2:
# fuse_gmock_files.py OUTPUT_DIR
FuseGMock(DEFAULT_GMOCK_ROOT_DIR, sys.argv[1])
elif argc == 3:
# fuse_gmock_files.py GMOCK_ROOT_DIR OUTPUT_DIR
FuseGMock(sys.argv[1], sys.argv[2])
else:
print __doc__
sys.exit(1)
if __name__ == '__main__':
main()
| Python |
# -*- Python -*-
# Copyright 2008 Google Inc. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Author: joi@google.com (Joi Sigurdsson)
# Author: vladl@google.com (Vlad Losev)
#
# Build file for Google Mock and its tests.
#
# Usage:
# cd to the directory with this file, then
# ./scons.py [OPTIONS]
#
# where frequently used command-line options include:
# -h print usage help.
# BUILD=all build all build types.
# BUILD=win-opt8 build the given build type.
EnsurePythonVersion(2, 3)
# Path to the Google Test code this Google Mock will use.
GTEST_DIR = '../gtest'
# TODO(vladl@google.com): Factor the looping logic out for reuse.
def BuildGMockSelectedEnvironments(sconstruct_helper):
# Build using whichever environments the 'BUILD' option selected
for build_name in sconstruct_helper.env_base['BUILD']:
print 'BUILDING %s' % build_name
env = sconstruct_helper.env_dict[build_name]
# Make sure SConscript files can refer to base build dir
env['MAIN_DIR'] = env.Dir(env['BUILD_DIR'])
#print 'CCFLAGS: %s' % env.subst('$CCFLAGS')
#print 'LINK: %s' % env.subst('$LINK')
#print 'AR: %s' % env.subst('$AR')
#print 'CC: %s' % env.subst('$CC')
#print 'CXX: %s' % env.subst('$CXX')
#print 'LIBPATH: %s' % env.subst('$LIBPATH')
#print 'ENV:PATH: %s' % env['ENV']['PATH']
#print 'ENV:INCLUDE: %s' % env['ENV']['INCLUDE']
#print 'ENV:LIB: %s' % env['ENV']['LIB']
#print 'ENV:TEMP: %s' % env['ENV']['TEMP']
env['GTEST_DIR'] = '#/' + GTEST_DIR
env['GTEST_BUILD_TESTS'] = False
Export('env')
# Invokes SConscript with variant_dir being build/<config name>.
# Counter-intuitively, src_dir is relative to the build dir and has
# to be '../..' to point to the scons directory.
VariantDir(env['BUILD_DIR'], '../..', duplicate=0)
gtest_exports = env.SConscript(env['BUILD_DIR'] + '/gtest/scons/SConscript')
Export('gtest_exports')
SConscript('SConscript',
src_dir='../..',
variant_dir=env['BUILD_DIR'],
duplicate=0)
sconstruct_helper = SConscript(GTEST_DIR + '/scons/SConstruct.common')
sconstruct_helper.Initialize(build_root_path='..',
support_multiple_win_builds=False)
win_base = sconstruct_helper.MakeWinBaseEnvironment()
sconstruct_helper.MakeWinDebugEnvironment(win_base, 'win-dbg8')
sconstruct_helper.MakeWinOptimizedEnvironment(win_base, 'win-opt8')
sconstruct_helper.ConfigureGccEnvironments()
BuildGMockSelectedEnvironments(sconstruct_helper)
| Python |
# -*- Python -*-
#
# Copyright 2008 Google Inc. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Builds the Google Mock (gmock) lib.
You should be able to call this file from more or less any SConscript
file.
You can optionally set a variable on the construction environment to
have the unit test executables copied to your output directory. The
variable should be env['EXE_OUTPUT'].
Another optional variable is env['LIB_OUTPUT']. If set, the generated
libraries are copied to the folder indicated by the variable.
If you place the Google Mock sources within your own project's source
directory, you should be able to call this SConscript file simply as
follows:
# -- cut here --
# Build gmock library; first tell it where to copy executables.
env['EXE_OUTPUT'] = '#/mybuilddir/mybuildmode' # example, optional
env['LIB_OUTPUT'] = '#/mybuilddir/mybuildmode/lib'
env.SConscript('whateverpath/gmock/scons/SConscript')
# -- cut here --
If on the other hand you place the Google Mock sources in a directory
outside of your project's source tree, you would use a snippet similar
to the following:
# -- cut here --
# The following assumes that $BUILD_DIR refers to the root of the
# directory for your current build mode, e.g. "#/mybuilddir/mybuildmode"
# Build gmock library; as it is outside of our source root, we need to
# tell SCons that the directory it will refer to as
# e.g. $BUILD_DIR/gmock is actually on disk in original form as
# ../../gmock (relative to your project root directory). Recall that
# SCons by default copies all source files into the build directory
# before building.
gmock_dir = env.Dir('$BUILD_DIR/gmock')
# Modify this part to point to Google Mock relative to the current
# SConscript or SConstruct file's directory. The ../.. path would
# be different per project, to locate the base directory for Google Mock.
gmock_dir.addRepository(env.Dir('../../gmock'))
# Tell the Google Mock SCons file where to copy executables.
env['EXE_OUTPUT'] = '$BUILD_DIR' # example, optional
# Call the Google Mock SConscript to build gmock.lib and unit tests. The
# location of the library should end up as
# '$BUILD_DIR/gmock/scons/gmock.lib'
env.SConscript(env.File('scons/SConscript', gmock_dir))
# -- cut here --
"""
__author__ = 'joi@google.com (Joi Sigurdsson)'
import os
############################################################
# Environments for building the targets, sorted by name.
Import('env', 'gtest_exports')
GTEST_DIR = env['GTEST_DIR']
GtestObject = gtest_exports['GtestObject']
GtestBinary = gtest_exports['GtestBinary']
GtestTest = gtest_exports['GtestTest']
gtest_common_exports = SConscript(GTEST_DIR + '/scons/SConscript.common')
EnvCreator = gtest_common_exports['EnvCreator']
env = env.Clone()
if env['PLATFORM'] == 'win32':
env.Append(CCFLAGS=[
'-wd4127', # Disables warning "conditional expression is constant",
# triggered by VC 8.0's own STL header <list>.
])
# Note: The relative paths in SConscript files are relative to the location
# of the SConscript file itself. To make a path relative to the location of
# the main SConstruct file, prepend the path with the # sign.
#
# Include paths to gtest headers are relative to either the gmock
# directory or the 'include' subdirectory of it, and this SConscript
# file is one directory deeper than the gmock directory.
env.Prepend(CPPPATH = ['..', '../include', GTEST_DIR + '/include'])
env_use_own_tuple = EnvCreator.Create(env, EnvCreator.UseOwnTuple)
env_with_exceptions = EnvCreator.Create(env, EnvCreator.WithExceptions)
env_without_rtti = EnvCreator.Create(env, EnvCreator.NoRtti)
############################################################
# Helpers for creating build targets.
def GmockStaticLibraries(build_env):
"""Builds static libraries for gmock and gmock_main in build_env.
Args:
build_env: An environment in which to build libraries.
Returns:
A pair (gmock_library, gmock_main_library) built in the build_env
environment.
"""
gmock_object = GtestObject(build_env, '../src/gmock-all.cc')
gmock_main_object = GtestObject(build_env, '../src/gmock_main.cc')
return (build_env.StaticLibrary(target='gmock' + build_env['OBJ_SUFFIX'],
source=[gmock_object]),
build_env.StaticLibrary(target='gmock_main' + build_env['OBJ_SUFFIX'],
source=[gmock_object, gmock_main_object]))
############################################################
# Object and library targets.
gtest = gtest_exports['gtest']
gtest_ex = gtest_exports['gtest_ex']
gtest_no_rtti = gtest_exports['gtest_no_rtti']
gtest_use_own_tuple = gtest_exports['gtest_use_own_tuple']
# gmock.lib to be used by most apps (if you have your own main function).
# gmock_main.lib can be used if you just want a basic main function; it is
# also used by some tests for Google Test itself.
gmock, gmock_main = GmockStaticLibraries(env)
gmock_ex, gmock_main_ex = GmockStaticLibraries(env_with_exceptions)
gmock_no_rtti, gmock_main_no_rtti = GmockStaticLibraries(env_without_rtti)
gmock_use_own_tuple, gmock_main_use_own_tuple = GmockStaticLibraries(
env_use_own_tuple)
# Install the libraries if needed.
if 'LIB_OUTPUT' in env.Dictionary():
env.Install('$LIB_OUTPUT', source=[gmock, gmock_main,
gmock_ex, gmock_main_ex,
gmock_no_rtti, gmock_main_no_rtti,
gmock_use_own_tuple,
gmock_main_use_own_tuple])
#############################################################
# Test targets using the standard environment.
GtestTest(env, 'gmock-actions_test', [gtest, gmock_main])
GtestTest(env, 'gmock-cardinalities_test', [gtest, gmock_main])
GtestTest(env, 'gmock-generated-actions_test', [gtest, gmock_main])
GtestTest(env, 'gmock-generated-function-mockers_test', [gtest, gmock_main])
GtestTest(env, 'gmock-generated-internal-utils_test', [gtest, gmock_main])
GtestTest(env, 'gmock-generated-matchers_test', [gtest, gmock_main])
GtestTest(env, 'gmock-internal-utils_test', [gtest, gmock_main])
GtestTest(env, 'gmock-matchers_test', [gtest, gmock_main])
GtestTest(env, 'gmock-more-actions_test', [gtest, gmock_main])
GtestTest(env, 'gmock-nice-strict_test', [gtest, gmock_main])
GtestTest(env, 'gmock-port_test', [gtest, gmock_main])
GtestTest(env, 'gmock-spec-builders_test', [gtest, gmock_main])
GtestTest(env, 'gmock_leak_test_', [gtest, gmock_main])
GtestTest(env, 'gmock_link_test', [gtest, gmock_main],
['../test/gmock_link2_test.cc'])
GtestTest(env, 'gmock_output_test_', [gtest, gmock])
#GtestTest(env, 'gmock_stress_test', [gtest, gmock])
GtestTest(env, 'gmock_test', [gtest, gmock_main])
# gmock_all_test is commented to save time building and running tests.
# Uncomment if necessary.
#GtestTest(env, 'gmock_all_test', [gtest, gmock_main])
############################################################
# Tests targets using custom environments.
GtestBinary(env_with_exceptions,
'gmock-more-actions-ex_test',
[gtest_ex, gmock_main_ex],
['../test/gmock-more-actions_test.cc'])
GtestBinary(env_without_rtti,
'gmock_no_rtti_test',
[gtest_no_rtti, gmock_main_no_rtti],
['../test/gmock-spec-builders_test.cc'])
GtestBinary(env_use_own_tuple,
'gmock_use_own_tuple_test',
[gtest_use_own_tuple, gmock_main_use_own_tuple],
['../test/gmock-spec-builders_test.cc'])
| Python |
#!/usr/bin/env python
#
# Copyright 2009 Google Inc. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests for run_tests_util.py test runner script."""
__author__ = 'vladl@google.com (Vlad Losev)'
import os
import re
import sets
import unittest
import run_tests_util
GTEST_DBG_DIR = 'scons/build/dbg/gtest/scons'
GTEST_OPT_DIR = 'scons/build/opt/gtest/scons'
GTEST_OTHER_DIR = 'scons/build/other/gtest/scons'
def AddExeExtension(path):
"""Appends .exe to the path on Windows or Cygwin."""
if run_tests_util.IS_WINDOWS or run_tests_util.IS_CYGWIN:
return path + '.exe'
else:
return path
class FakePath(object):
"""A fake os.path module for testing."""
def __init__(self, current_dir=os.getcwd(), known_paths=None):
self.current_dir = current_dir
self.tree = {}
self.path_separator = os.sep
# known_paths contains either absolute or relative paths. Relative paths
# are absolutized with self.current_dir.
if known_paths:
self._AddPaths(known_paths)
def _AddPath(self, path):
ends_with_slash = path.endswith('/')
path = self.abspath(path)
if ends_with_slash:
path += self.path_separator
name_list = path.split(self.path_separator)
tree = self.tree
for name in name_list[:-1]:
if not name:
continue
if name in tree:
tree = tree[name]
else:
tree[name] = {}
tree = tree[name]
name = name_list[-1]
if name:
if name in tree:
assert tree[name] == 1
else:
tree[name] = 1
def _AddPaths(self, paths):
for path in paths:
self._AddPath(path)
def PathElement(self, path):
"""Returns an internal representation of directory tree entry for path."""
tree = self.tree
name_list = self.abspath(path).split(self.path_separator)
for name in name_list:
if not name:
continue
tree = tree.get(name, None)
if tree is None:
break
return tree
# Silences pylint warning about using standard names.
# pylint: disable-msg=C6409
def normpath(self, path):
return os.path.normpath(path)
def abspath(self, path):
return self.normpath(os.path.join(self.current_dir, path))
def isfile(self, path):
return self.PathElement(self.abspath(path)) == 1
def isdir(self, path):
return type(self.PathElement(self.abspath(path))) == type(dict())
def basename(self, path):
return os.path.basename(path)
def dirname(self, path):
return os.path.dirname(path)
def join(self, *kargs):
return os.path.join(*kargs)
class FakeOs(object):
"""A fake os module for testing."""
P_WAIT = os.P_WAIT
def __init__(self, fake_path_module):
self.path = fake_path_module
# Some methods/attributes are delegated to the real os module.
self.environ = os.environ
# pylint: disable-msg=C6409
def listdir(self, path):
assert self.path.isdir(path)
return self.path.PathElement(path).iterkeys()
def spawnv(self, wait, executable, *kargs):
assert wait == FakeOs.P_WAIT
return self.spawn_impl(executable, kargs)
class GetTestsToRunTest(unittest.TestCase):
"""Exercises TestRunner.GetTestsToRun."""
def NormalizeGetTestsToRunResults(self, results):
"""Normalizes path data returned from GetTestsToRun for comparison."""
def NormalizePythonTestPair(pair):
"""Normalizes path data in the (directory, python_script) pair."""
return (os.path.normpath(pair[0]), os.path.normpath(pair[1]))
def NormalizeBinaryTestPair(pair):
"""Normalizes path data in the (directory, binary_executable) pair."""
directory, executable = map(os.path.normpath, pair)
# On Windows and Cygwin, the test file names have the .exe extension, but
# they can be invoked either by name or by name+extension. Our test must
# accommodate both situations.
if run_tests_util.IS_WINDOWS or run_tests_util.IS_CYGWIN:
executable = re.sub(r'\.exe$', '', executable)
return (directory, executable)
python_tests = sets.Set(map(NormalizePythonTestPair, results[0]))
binary_tests = sets.Set(map(NormalizeBinaryTestPair, results[1]))
return (python_tests, binary_tests)
def AssertResultsEqual(self, results, expected):
"""Asserts results returned by GetTestsToRun equal to expected results."""
self.assertEqual(self.NormalizeGetTestsToRunResults(results),
self.NormalizeGetTestsToRunResults(expected),
'Incorrect set of tests returned:\n%s\nexpected:\n%s' %
(results, expected))
def setUp(self):
self.fake_os = FakeOs(FakePath(
current_dir=os.path.abspath(os.path.dirname(run_tests_util.__file__)),
known_paths=[AddExeExtension(GTEST_DBG_DIR + '/gtest_unittest'),
AddExeExtension(GTEST_OPT_DIR + '/gtest_unittest'),
'test/gtest_color_test.py']))
self.fake_configurations = ['dbg', 'opt']
self.test_runner = run_tests_util.TestRunner(script_dir='.',
injected_os=self.fake_os,
injected_subprocess=None)
def testBinaryTestsOnly(self):
"""Exercises GetTestsToRun with parameters designating binary tests only."""
# A default build.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
['gtest_unittest'],
'',
False,
available_configurations=self.fake_configurations),
([],
[(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')]))
# An explicitly specified directory.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
[GTEST_DBG_DIR, 'gtest_unittest'],
'',
False,
available_configurations=self.fake_configurations),
([],
[(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')]))
# A particular configuration.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
['gtest_unittest'],
'other',
False,
available_configurations=self.fake_configurations),
([],
[(GTEST_OTHER_DIR, GTEST_OTHER_DIR + '/gtest_unittest')]))
# All available configurations
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
['gtest_unittest'],
'all',
False,
available_configurations=self.fake_configurations),
([],
[(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest'),
(GTEST_OPT_DIR, GTEST_OPT_DIR + '/gtest_unittest')]))
# All built configurations (unbuilt don't cause failure).
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
['gtest_unittest'],
'',
True,
available_configurations=self.fake_configurations + ['unbuilt']),
([],
[(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest'),
(GTEST_OPT_DIR, GTEST_OPT_DIR + '/gtest_unittest')]))
# A combination of an explicit directory and a configuration.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
[GTEST_DBG_DIR, 'gtest_unittest'],
'opt',
False,
available_configurations=self.fake_configurations),
([],
[(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest'),
(GTEST_OPT_DIR, GTEST_OPT_DIR + '/gtest_unittest')]))
# Same test specified in an explicit directory and via a configuration.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
[GTEST_DBG_DIR, 'gtest_unittest'],
'dbg',
False,
available_configurations=self.fake_configurations),
([],
[(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')]))
# All built configurations + explicit directory + explicit configuration.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
[GTEST_DBG_DIR, 'gtest_unittest'],
'opt',
True,
available_configurations=self.fake_configurations),
([],
[(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest'),
(GTEST_OPT_DIR, GTEST_OPT_DIR + '/gtest_unittest')]))
def testPythonTestsOnly(self):
"""Exercises GetTestsToRun with parameters designating Python tests only."""
# A default build.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
['gtest_color_test.py'],
'',
False,
available_configurations=self.fake_configurations),
([(GTEST_DBG_DIR, 'test/gtest_color_test.py')],
[]))
# An explicitly specified directory.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
[GTEST_DBG_DIR, 'test/gtest_color_test.py'],
'',
False,
available_configurations=self.fake_configurations),
([(GTEST_DBG_DIR, 'test/gtest_color_test.py')],
[]))
# A particular configuration.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
['gtest_color_test.py'],
'other',
False,
available_configurations=self.fake_configurations),
([(GTEST_OTHER_DIR, 'test/gtest_color_test.py')],
[]))
# All available configurations
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
['test/gtest_color_test.py'],
'all',
False,
available_configurations=self.fake_configurations),
([(GTEST_DBG_DIR, 'test/gtest_color_test.py'),
(GTEST_OPT_DIR, 'test/gtest_color_test.py')],
[]))
# All built configurations (unbuilt don't cause failure).
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
['gtest_color_test.py'],
'',
True,
available_configurations=self.fake_configurations + ['unbuilt']),
([(GTEST_DBG_DIR, 'test/gtest_color_test.py'),
(GTEST_OPT_DIR, 'test/gtest_color_test.py')],
[]))
# A combination of an explicit directory and a configuration.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
[GTEST_DBG_DIR, 'gtest_color_test.py'],
'opt',
False,
available_configurations=self.fake_configurations),
([(GTEST_DBG_DIR, 'test/gtest_color_test.py'),
(GTEST_OPT_DIR, 'test/gtest_color_test.py')],
[]))
# Same test specified in an explicit directory and via a configuration.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
[GTEST_DBG_DIR, 'gtest_color_test.py'],
'dbg',
False,
available_configurations=self.fake_configurations),
([(GTEST_DBG_DIR, 'test/gtest_color_test.py')],
[]))
# All built configurations + explicit directory + explicit configuration.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
[GTEST_DBG_DIR, 'gtest_color_test.py'],
'opt',
True,
available_configurations=self.fake_configurations),
([(GTEST_DBG_DIR, 'test/gtest_color_test.py'),
(GTEST_OPT_DIR, 'test/gtest_color_test.py')],
[]))
def testCombinationOfBinaryAndPythonTests(self):
"""Exercises GetTestsToRun with mixed binary/Python tests."""
# Use only default configuration for this test.
# Neither binary nor Python tests are specified so find all.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
[],
'',
False,
available_configurations=self.fake_configurations),
([(GTEST_DBG_DIR, 'test/gtest_color_test.py')],
[(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')]))
# Specifying both binary and Python tests.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
['gtest_unittest', 'gtest_color_test.py'],
'',
False,
available_configurations=self.fake_configurations),
([(GTEST_DBG_DIR, 'test/gtest_color_test.py')],
[(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')]))
# Specifying binary tests suppresses Python tests.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
['gtest_unittest'],
'',
False,
available_configurations=self.fake_configurations),
([],
[(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')]))
# Specifying Python tests suppresses binary tests.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
['gtest_color_test.py'],
'',
False,
available_configurations=self.fake_configurations),
([(GTEST_DBG_DIR, 'test/gtest_color_test.py')],
[]))
def testIgnoresNonTestFiles(self):
"""Verifies that GetTestsToRun ignores non-test files in the filesystem."""
self.fake_os = FakeOs(FakePath(
current_dir=os.path.abspath(os.path.dirname(run_tests_util.__file__)),
known_paths=[AddExeExtension(GTEST_DBG_DIR + '/gtest_nontest'),
'test/']))
self.test_runner = run_tests_util.TestRunner(script_dir='.',
injected_os=self.fake_os,
injected_subprocess=None)
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
[],
'',
True,
available_configurations=self.fake_configurations),
([], []))
def testWorksFromDifferentDir(self):
"""Exercises GetTestsToRun from a directory different from run_test.py's."""
# Here we simulate an test script in directory /d/ called from the
# directory /a/b/c/.
self.fake_os = FakeOs(FakePath(
current_dir=os.path.abspath('/a/b/c'),
known_paths=[
'/a/b/c/',
AddExeExtension('/d/' + GTEST_DBG_DIR + '/gtest_unittest'),
AddExeExtension('/d/' + GTEST_OPT_DIR + '/gtest_unittest'),
'/d/test/gtest_color_test.py']))
self.fake_configurations = ['dbg', 'opt']
self.test_runner = run_tests_util.TestRunner(script_dir='/d/',
injected_os=self.fake_os,
injected_subprocess=None)
# A binary test.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
['gtest_unittest'],
'',
False,
available_configurations=self.fake_configurations),
([],
[('/d/' + GTEST_DBG_DIR, '/d/' + GTEST_DBG_DIR + '/gtest_unittest')]))
# A Python test.
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
['gtest_color_test.py'],
'',
False,
available_configurations=self.fake_configurations),
([('/d/' + GTEST_DBG_DIR, '/d/test/gtest_color_test.py')], []))
def testNonTestBinary(self):
"""Exercises GetTestsToRun with a non-test parameter."""
self.assert_(
not self.test_runner.GetTestsToRun(
['gtest_unittest_not_really'],
'',
False,
available_configurations=self.fake_configurations))
def testNonExistingPythonTest(self):
"""Exercises GetTestsToRun with a non-existent Python test parameter."""
self.assert_(
not self.test_runner.GetTestsToRun(
['nonexistent_test.py'],
'',
False,
available_configurations=self.fake_configurations))
if run_tests_util.IS_WINDOWS or run_tests_util.IS_CYGWIN:
def testDoesNotPickNonExeFilesOnWindows(self):
"""Verifies that GetTestsToRun does not find _test files on Windows."""
self.fake_os = FakeOs(FakePath(
current_dir=os.path.abspath(os.path.dirname(run_tests_util.__file__)),
known_paths=['/d/' + GTEST_DBG_DIR + '/gtest_test', 'test/']))
self.test_runner = run_tests_util.TestRunner(script_dir='.',
injected_os=self.fake_os,
injected_subprocess=None)
self.AssertResultsEqual(
self.test_runner.GetTestsToRun(
[],
'',
True,
available_configurations=self.fake_configurations),
([], []))
class RunTestsTest(unittest.TestCase):
"""Exercises TestRunner.RunTests."""
def SpawnSuccess(self, unused_executable, unused_argv):
"""Fakes test success by returning 0 as an exit code."""
self.num_spawn_calls += 1
return 0
def SpawnFailure(self, unused_executable, unused_argv):
"""Fakes test success by returning 1 as an exit code."""
self.num_spawn_calls += 1
return 1
def setUp(self):
self.fake_os = FakeOs(FakePath(
current_dir=os.path.abspath(os.path.dirname(run_tests_util.__file__)),
known_paths=[
AddExeExtension(GTEST_DBG_DIR + '/gtest_unittest'),
AddExeExtension(GTEST_OPT_DIR + '/gtest_unittest'),
'test/gtest_color_test.py']))
self.fake_configurations = ['dbg', 'opt']
self.test_runner = run_tests_util.TestRunner(
script_dir=os.path.dirname(__file__) or '.',
injected_os=self.fake_os,
injected_subprocess=None)
self.num_spawn_calls = 0 # A number of calls to spawn.
def testRunPythonTestSuccess(self):
"""Exercises RunTests to handle a Python test success."""
self.fake_os.spawn_impl = self.SpawnSuccess
self.assertEqual(
self.test_runner.RunTests(
[(GTEST_DBG_DIR, 'test/gtest_color_test.py')],
[]),
0)
self.assertEqual(self.num_spawn_calls, 1)
def testRunBinaryTestSuccess(self):
"""Exercises RunTests to handle a binary test success."""
self.fake_os.spawn_impl = self.SpawnSuccess
self.assertEqual(
self.test_runner.RunTests(
[],
[(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')]),
0)
self.assertEqual(self.num_spawn_calls, 1)
def testRunPythonTestFauilure(self):
"""Exercises RunTests to handle a Python test failure."""
self.fake_os.spawn_impl = self.SpawnFailure
self.assertEqual(
self.test_runner.RunTests(
[(GTEST_DBG_DIR, 'test/gtest_color_test.py')],
[]),
1)
self.assertEqual(self.num_spawn_calls, 1)
def testRunBinaryTestFailure(self):
"""Exercises RunTests to handle a binary test failure."""
self.fake_os.spawn_impl = self.SpawnFailure
self.assertEqual(
self.test_runner.RunTests(
[],
[(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')]),
1)
self.assertEqual(self.num_spawn_calls, 1)
def testCombinedTestSuccess(self):
"""Exercises RunTests to handle a success of both Python and binary test."""
self.fake_os.spawn_impl = self.SpawnSuccess
self.assertEqual(
self.test_runner.RunTests(
[(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')],
[(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')]),
0)
self.assertEqual(self.num_spawn_calls, 2)
def testCombinedTestSuccessAndFailure(self):
"""Exercises RunTests to handle a success of both Python and binary test."""
def SpawnImpl(executable, argv):
self.num_spawn_calls += 1
# Simulates failure of a Python test and success of a binary test.
if '.py' in executable or '.py' in argv[0]:
return 1
else:
return 0
self.fake_os.spawn_impl = SpawnImpl
self.assertEqual(
self.test_runner.RunTests(
[(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')],
[(GTEST_DBG_DIR, GTEST_DBG_DIR + '/gtest_unittest')]),
0)
self.assertEqual(self.num_spawn_calls, 2)
class ParseArgsTest(unittest.TestCase):
"""Exercises ParseArgs."""
def testNoOptions(self):
options, args = run_tests_util.ParseArgs('gtest', argv=['script.py'])
self.assertEqual(args, ['script.py'])
self.assert_(options.configurations is None)
self.assertFalse(options.built_configurations)
def testOptionC(self):
options, args = run_tests_util.ParseArgs(
'gtest', argv=['script.py', '-c', 'dbg'])
self.assertEqual(args, ['script.py'])
self.assertEqual(options.configurations, 'dbg')
self.assertFalse(options.built_configurations)
def testOptionA(self):
options, args = run_tests_util.ParseArgs('gtest', argv=['script.py', '-a'])
self.assertEqual(args, ['script.py'])
self.assertEqual(options.configurations, 'all')
self.assertFalse(options.built_configurations)
def testOptionB(self):
options, args = run_tests_util.ParseArgs('gtest', argv=['script.py', '-b'])
self.assertEqual(args, ['script.py'])
self.assert_(options.configurations is None)
self.assertTrue(options.built_configurations)
def testOptionCAndOptionB(self):
options, args = run_tests_util.ParseArgs(
'gtest', argv=['script.py', '-c', 'dbg', '-b'])
self.assertEqual(args, ['script.py'])
self.assertEqual(options.configurations, 'dbg')
self.assertTrue(options.built_configurations)
def testOptionH(self):
help_called = [False]
# Suppresses lint warning on unused arguments. These arguments are
# required by optparse, even though they are unused.
# pylint: disable-msg=W0613
def VerifyHelp(option, opt, value, parser):
help_called[0] = True
# Verifies that -h causes the help callback to be called.
help_called[0] = False
_, args = run_tests_util.ParseArgs(
'gtest', argv=['script.py', '-h'], help_callback=VerifyHelp)
self.assertEqual(args, ['script.py'])
self.assertTrue(help_called[0])
# Verifies that --help causes the help callback to be called.
help_called[0] = False
_, args = run_tests_util.ParseArgs(
'gtest', argv=['script.py', '--help'], help_callback=VerifyHelp)
self.assertEqual(args, ['script.py'])
self.assertTrue(help_called[0])
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test for the gtest_xml_output module."""
__author__ = "keith.ray@gmail.com (Keith Ray)"
import os
from xml.dom import minidom, Node
import gtest_test_utils
import gtest_xml_test_utils
GTEST_OUTPUT_SUBDIR = "xml_outfiles"
GTEST_OUTPUT_1_TEST = "gtest_xml_outfile1_test_"
GTEST_OUTPUT_2_TEST = "gtest_xml_outfile2_test_"
EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*" name="AllTests">
<testsuite name="PropertyOne" tests="1" failures="0" disabled="0" errors="0" time="*">
<testcase name="TestSomeProperties" status="run" time="*" classname="PropertyOne" SetUpProp="1" TestSomeProperty="1" TearDownProp="1" />
</testsuite>
</testsuites>
"""
EXPECTED_XML_2 = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*" name="AllTests">
<testsuite name="PropertyTwo" tests="1" failures="0" disabled="0" errors="0" time="*">
<testcase name="TestSomeProperties" status="run" time="*" classname="PropertyTwo" SetUpProp="2" TestSomeProperty="2" TearDownProp="2" />
</testsuite>
</testsuites>
"""
class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase):
"""Unit test for Google Test's XML output functionality."""
def setUp(self):
# We want the trailing '/' that the last "" provides in os.path.join, for
# telling Google Test to create an output directory instead of a single file
# for xml output.
self.output_dir_ = os.path.join(gtest_test_utils.GetTempDir(),
GTEST_OUTPUT_SUBDIR, "")
self.DeleteFilesAndDir()
def tearDown(self):
self.DeleteFilesAndDir()
def DeleteFilesAndDir(self):
try:
os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_1_TEST + ".xml"))
except os.error:
pass
try:
os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_2_TEST + ".xml"))
except os.error:
pass
try:
os.rmdir(self.output_dir_)
except os.error:
pass
def testOutfile1(self):
self._TestOutFile(GTEST_OUTPUT_1_TEST, EXPECTED_XML_1)
def testOutfile2(self):
self._TestOutFile(GTEST_OUTPUT_2_TEST, EXPECTED_XML_2)
def _TestOutFile(self, test_name, expected_xml):
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(test_name)
command = [gtest_prog_path, "--gtest_output=xml:%s" % self.output_dir_]
p = gtest_test_utils.Subprocess(command,
working_dir=gtest_test_utils.GetTempDir())
self.assert_(p.exited)
self.assertEquals(0, p.exit_code)
# TODO(wan@google.com): libtool causes the built test binary to be
# named lt-gtest_xml_outfiles_test_ instead of
# gtest_xml_outfiles_test_. To account for this possibillity, we
# allow both names in the following code. We should remove this
# hack when Chandler Carruth's libtool replacement tool is ready.
output_file_name1 = test_name + ".xml"
output_file1 = os.path.join(self.output_dir_, output_file_name1)
output_file_name2 = 'lt-' + output_file_name1
output_file2 = os.path.join(self.output_dir_, output_file_name2)
self.assert_(os.path.isfile(output_file1) or os.path.isfile(output_file2),
output_file1)
expected = minidom.parseString(expected_xml)
if os.path.isfile(output_file1):
actual = minidom.parse(output_file1)
else:
actual = minidom.parse(output_file2)
self.NormalizeXml(actual.documentElement)
self.AssertEquivalentNodes(expected.documentElement,
actual.documentElement)
expected.unlink()
actual.unlink()
if __name__ == "__main__":
os.environ["GTEST_STACK_TRACE_DEPTH"] = "0"
gtest_test_utils.Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2009, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests the --help flag of Google C++ Testing Framework.
SYNOPSIS
gtest_help_test.py --build_dir=BUILD/DIR
# where BUILD/DIR contains the built gtest_help_test_ file.
gtest_help_test.py
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import re
import gtest_test_utils
IS_WINDOWS = os.name == 'nt'
PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_help_test_')
FLAG_PREFIX = '--gtest_'
CATCH_EXCEPTIONS_FLAG = FLAG_PREFIX + 'catch_exceptions'
DEATH_TEST_STYLE_FLAG = FLAG_PREFIX + 'death_test_style'
UNKNOWN_FLAG = FLAG_PREFIX + 'unknown_flag_for_testing'
LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests'
INCORRECT_FLAG_VARIANTS = [re.sub('^--', '-', LIST_TESTS_FLAG),
re.sub('^--', '/', LIST_TESTS_FLAG),
re.sub('_', '-', LIST_TESTS_FLAG)]
INTERNAL_FLAG_FOR_TESTING = FLAG_PREFIX + 'internal_flag_for_testing'
SUPPORTS_DEATH_TESTS = "DeathTest" in gtest_test_utils.Subprocess(
[PROGRAM_PATH, LIST_TESTS_FLAG]).output
# The help message must match this regex.
HELP_REGEX = re.compile(
FLAG_PREFIX + r'list_tests.*' +
FLAG_PREFIX + r'filter=.*' +
FLAG_PREFIX + r'also_run_disabled_tests.*' +
FLAG_PREFIX + r'repeat=.*' +
FLAG_PREFIX + r'shuffle.*' +
FLAG_PREFIX + r'random_seed=.*' +
FLAG_PREFIX + r'color=.*' +
FLAG_PREFIX + r'print_time.*' +
FLAG_PREFIX + r'output=.*' +
FLAG_PREFIX + r'break_on_failure.*' +
FLAG_PREFIX + r'throw_on_failure.*',
re.DOTALL)
def RunWithFlag(flag):
"""Runs gtest_help_test_ with the given flag.
Returns:
the exit code and the text output as a tuple.
Args:
flag: the command-line flag to pass to gtest_help_test_, or None.
"""
if flag is None:
command = [PROGRAM_PATH]
else:
command = [PROGRAM_PATH, flag]
child = gtest_test_utils.Subprocess(command)
return child.exit_code, child.output
class GTestHelpTest(gtest_test_utils.TestCase):
"""Tests the --help flag and its equivalent forms."""
def TestHelpFlag(self, flag):
"""Verifies correct behavior when help flag is specified.
The right message must be printed and the tests must
skipped when the given flag is specified.
Args:
flag: A flag to pass to the binary or None.
"""
exit_code, output = RunWithFlag(flag)
self.assertEquals(0, exit_code)
self.assert_(HELP_REGEX.search(output), output)
if IS_WINDOWS:
self.assert_(CATCH_EXCEPTIONS_FLAG in output, output)
else:
self.assert_(CATCH_EXCEPTIONS_FLAG not in output, output)
if SUPPORTS_DEATH_TESTS and not IS_WINDOWS:
self.assert_(DEATH_TEST_STYLE_FLAG in output, output)
else:
self.assert_(DEATH_TEST_STYLE_FLAG not in output, output)
def TestNonHelpFlag(self, flag):
"""Verifies correct behavior when no help flag is specified.
Verifies that when no help flag is specified, the tests are run
and the help message is not printed.
Args:
flag: A flag to pass to the binary or None.
"""
exit_code, output = RunWithFlag(flag)
self.assert_(exit_code != 0)
self.assert_(not HELP_REGEX.search(output), output)
def testPrintsHelpWithFullFlag(self):
self.TestHelpFlag('--help')
def testPrintsHelpWithShortFlag(self):
self.TestHelpFlag('-h')
def testPrintsHelpWithQuestionFlag(self):
self.TestHelpFlag('-?')
def testPrintsHelpWithWindowsStyleQuestionFlag(self):
self.TestHelpFlag('/?')
def testPrintsHelpWithUnrecognizedGoogleTestFlag(self):
self.TestHelpFlag(UNKNOWN_FLAG)
def testPrintsHelpWithIncorrectFlagStyle(self):
for incorrect_flag in INCORRECT_FLAG_VARIANTS:
self.TestHelpFlag(incorrect_flag)
def testRunsTestsWithoutHelpFlag(self):
"""Verifies that when no help flag is specified, the tests are run
and the help message is not printed."""
self.TestNonHelpFlag(None)
def testRunsTestsWithGtestInternalFlag(self):
"""Verifies that the tests are run and no help message is printed when
a flag starting with Google Test prefix and 'internal_' is supplied."""
self.TestNonHelpFlag(INTERNAL_FLAG_FOR_TESTING)
if __name__ == '__main__':
gtest_test_utils.Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Verifies that Google Test correctly determines whether to use colors."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import gtest_test_utils
IS_WINDOWS = os.name = 'nt'
COLOR_ENV_VAR = 'GTEST_COLOR'
COLOR_FLAG = 'gtest_color'
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_color_test_')
def SetEnvVar(env_var, value):
"""Sets the env variable to 'value'; unsets it when 'value' is None."""
if value is not None:
os.environ[env_var] = value
elif env_var in os.environ:
del os.environ[env_var]
def UsesColor(term, color_env_var, color_flag):
"""Runs gtest_color_test_ and returns its exit code."""
SetEnvVar('TERM', term)
SetEnvVar(COLOR_ENV_VAR, color_env_var)
if color_flag is None:
args = []
else:
args = ['--%s=%s' % (COLOR_FLAG, color_flag)]
p = gtest_test_utils.Subprocess([COMMAND] + args)
return not p.exited or p.exit_code
class GTestColorTest(gtest_test_utils.TestCase):
def testNoEnvVarNoFlag(self):
"""Tests the case when there's neither GTEST_COLOR nor --gtest_color."""
if not IS_WINDOWS:
self.assert_(not UsesColor('dumb', None, None))
self.assert_(not UsesColor('emacs', None, None))
self.assert_(not UsesColor('xterm-mono', None, None))
self.assert_(not UsesColor('unknown', None, None))
self.assert_(not UsesColor(None, None, None))
self.assert_(UsesColor('linux', None, None))
self.assert_(UsesColor('cygwin', None, None))
self.assert_(UsesColor('xterm', None, None))
self.assert_(UsesColor('xterm-color', None, None))
self.assert_(UsesColor('xterm-256color', None, None))
def testFlagOnly(self):
"""Tests the case when there's --gtest_color but not GTEST_COLOR."""
self.assert_(not UsesColor('dumb', None, 'no'))
self.assert_(not UsesColor('xterm-color', None, 'no'))
if not IS_WINDOWS:
self.assert_(not UsesColor('emacs', None, 'auto'))
self.assert_(UsesColor('xterm', None, 'auto'))
self.assert_(UsesColor('dumb', None, 'yes'))
self.assert_(UsesColor('xterm', None, 'yes'))
def testEnvVarOnly(self):
"""Tests the case when there's GTEST_COLOR but not --gtest_color."""
self.assert_(not UsesColor('dumb', 'no', None))
self.assert_(not UsesColor('xterm-color', 'no', None))
if not IS_WINDOWS:
self.assert_(not UsesColor('dumb', 'auto', None))
self.assert_(UsesColor('xterm-color', 'auto', None))
self.assert_(UsesColor('dumb', 'yes', None))
self.assert_(UsesColor('xterm-color', 'yes', None))
def testEnvVarAndFlag(self):
"""Tests the case when there are both GTEST_COLOR and --gtest_color."""
self.assert_(not UsesColor('xterm-color', 'no', 'no'))
self.assert_(UsesColor('dumb', 'no', 'yes'))
self.assert_(UsesColor('xterm-color', 'no', 'auto'))
def testAliasesOfYesAndNo(self):
"""Tests using aliases in specifying --gtest_color."""
self.assert_(UsesColor('dumb', None, 'true'))
self.assert_(UsesColor('dumb', None, 'YES'))
self.assert_(UsesColor('dumb', None, 'T'))
self.assert_(UsesColor('dumb', None, '1'))
self.assert_(not UsesColor('xterm', None, 'f'))
self.assert_(not UsesColor('xterm', None, 'false'))
self.assert_(not UsesColor('xterm', None, '0'))
self.assert_(not UsesColor('xterm', None, 'unknown'))
if __name__ == '__main__':
gtest_test_utils.Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2007, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Negative compilation test for Google Test."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import sys
import unittest
IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
if not IS_LINUX:
sys.exit(0) # Negative compilation tests are not supported on Windows & Mac.
class GTestNCTest(unittest.TestCase):
"""Negative compilation test for Google Test."""
def testCompilerError(self):
"""Verifies that erroneous code leads to expected compiler
messages."""
# Defines a list of test specs, where each element is a tuple
# (test name, list of regexes for matching the compiler errors).
test_specs = [
('CANNOT_IGNORE_RUN_ALL_TESTS_RESULT',
[r'ignoring return value']),
('USER_CANNOT_INCLUDE_GTEST_INTERNAL_INL_H',
[r'must not be included except by Google Test itself']),
('CATCHES_DECLARING_SETUP_IN_TEST_FIXTURE_WITH_TYPO',
[r'Setup_should_be_spelled_SetUp']),
('CATCHES_CALLING_SETUP_IN_TEST_WITH_TYPO',
[r'Setup_should_be_spelled_SetUp']),
('CATCHES_DECLARING_SETUP_IN_ENVIRONMENT_WITH_TYPO',
[r'Setup_should_be_spelled_SetUp']),
('CATCHES_CALLING_SETUP_IN_ENVIRONMENT_WITH_TYPO',
[r'Setup_should_be_spelled_SetUp']),
('CATCHES_WRONG_CASE_IN_TYPED_TEST_P',
[r'BarTest.*was not declared']),
('CATCHES_WRONG_CASE_IN_REGISTER_TYPED_TEST_CASE_P',
[r'BarTest.*was not declared']),
('CATCHES_WRONG_CASE_IN_INSTANTIATE_TYPED_TEST_CASE_P',
[r'BarTest.*not declared']),
('CATCHES_INSTANTIATE_TYPED_TESET_CASE_P_WITH_SAME_NAME_PREFIX',
[r'redefinition of.*My.*FooTest']),
('STATIC_ASSERT_TYPE_EQ_IS_NOT_A_TYPE',
[r'StaticAssertTypeEq.* does not name a type']),
('STATIC_ASSERT_TYPE_EQ_WORKS_IN_NAMESPACE',
[r'StaticAssertTypeEq.*int.*const int']),
('STATIC_ASSERT_TYPE_EQ_WORKS_IN_CLASS',
[r'StaticAssertTypeEq.*int.*bool']),
('STATIC_ASSERT_TYPE_EQ_WORKS_IN_FUNCTION',
[r'StaticAssertTypeEq.*const int.*int']),
('SANITY',
None)
]
# TODO(wan@google.com): verify that the test specs are satisfied.
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test for Google Test's break-on-failure mode.
A user can ask Google Test to seg-fault when an assertion fails, using
either the GTEST_BREAK_ON_FAILURE environment variable or the
--gtest_break_on_failure flag. This script tests such functionality
by invoking gtest_break_on_failure_unittest_ (a program written with
Google Test) with different environments and command line flags.
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import gtest_test_utils
import os
import sys
# Constants.
IS_WINDOWS = os.name == 'nt'
# The environment variable for enabling/disabling the break-on-failure mode.
BREAK_ON_FAILURE_ENV_VAR = 'GTEST_BREAK_ON_FAILURE'
# The command line flag for enabling/disabling the break-on-failure mode.
BREAK_ON_FAILURE_FLAG = 'gtest_break_on_failure'
# The environment variable for enabling/disabling the throw-on-failure mode.
THROW_ON_FAILURE_ENV_VAR = 'GTEST_THROW_ON_FAILURE'
# The environment variable for enabling/disabling the catch-exceptions mode.
CATCH_EXCEPTIONS_ENV_VAR = 'GTEST_CATCH_EXCEPTIONS'
# Path to the gtest_break_on_failure_unittest_ program.
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
'gtest_break_on_failure_unittest_')
# Utilities.
environ = os.environ.copy()
def SetEnvVar(env_var, value):
"""Sets an environment variable to a given value; unsets it when the
given value is None.
"""
if value is not None:
environ[env_var] = value
elif env_var in environ:
del environ[env_var]
def Run(command):
"""Runs a command; returns 1 if it was killed by a signal, or 0 otherwise."""
p = gtest_test_utils.Subprocess(command, env=environ)
if p.terminated_by_signal:
return 1
else:
return 0
# The tests.
class GTestBreakOnFailureUnitTest(gtest_test_utils.TestCase):
"""Tests using the GTEST_BREAK_ON_FAILURE environment variable or
the --gtest_break_on_failure flag to turn assertion failures into
segmentation faults.
"""
def RunAndVerify(self, env_var_value, flag_value, expect_seg_fault):
"""Runs gtest_break_on_failure_unittest_ and verifies that it does
(or does not) have a seg-fault.
Args:
env_var_value: value of the GTEST_BREAK_ON_FAILURE environment
variable; None if the variable should be unset.
flag_value: value of the --gtest_break_on_failure flag;
None if the flag should not be present.
expect_seg_fault: 1 if the program is expected to generate a seg-fault;
0 otherwise.
"""
SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, env_var_value)
if env_var_value is None:
env_var_value_msg = ' is not set'
else:
env_var_value_msg = '=' + env_var_value
if flag_value is None:
flag = ''
elif flag_value == '0':
flag = '--%s=0' % BREAK_ON_FAILURE_FLAG
else:
flag = '--%s' % BREAK_ON_FAILURE_FLAG
command = [EXE_PATH]
if flag:
command.append(flag)
if expect_seg_fault:
should_or_not = 'should'
else:
should_or_not = 'should not'
has_seg_fault = Run(command)
SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, None)
msg = ('when %s%s, an assertion failure in "%s" %s cause a seg-fault.' %
(BREAK_ON_FAILURE_ENV_VAR, env_var_value_msg, ' '.join(command),
should_or_not))
self.assert_(has_seg_fault == expect_seg_fault, msg)
def testDefaultBehavior(self):
"""Tests the behavior of the default mode."""
self.RunAndVerify(env_var_value=None,
flag_value=None,
expect_seg_fault=0)
def testEnvVar(self):
"""Tests using the GTEST_BREAK_ON_FAILURE environment variable."""
self.RunAndVerify(env_var_value='0',
flag_value=None,
expect_seg_fault=0)
self.RunAndVerify(env_var_value='1',
flag_value=None,
expect_seg_fault=1)
def testFlag(self):
"""Tests using the --gtest_break_on_failure flag."""
self.RunAndVerify(env_var_value=None,
flag_value='0',
expect_seg_fault=0)
self.RunAndVerify(env_var_value=None,
flag_value='1',
expect_seg_fault=1)
def testFlagOverridesEnvVar(self):
"""Tests that the flag overrides the environment variable."""
self.RunAndVerify(env_var_value='0',
flag_value='0',
expect_seg_fault=0)
self.RunAndVerify(env_var_value='0',
flag_value='1',
expect_seg_fault=1)
self.RunAndVerify(env_var_value='1',
flag_value='0',
expect_seg_fault=0)
self.RunAndVerify(env_var_value='1',
flag_value='1',
expect_seg_fault=1)
def testBreakOnFailureOverridesThrowOnFailure(self):
"""Tests that gtest_break_on_failure overrides gtest_throw_on_failure."""
SetEnvVar(THROW_ON_FAILURE_ENV_VAR, '1')
try:
self.RunAndVerify(env_var_value=None,
flag_value='1',
expect_seg_fault=1)
finally:
SetEnvVar(THROW_ON_FAILURE_ENV_VAR, None)
if IS_WINDOWS:
def testCatchExceptionsDoesNotInterfere(self):
"""Tests that gtest_catch_exceptions doesn't interfere."""
SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, '1')
try:
self.RunAndVerify(env_var_value='1',
flag_value='1',
expect_seg_fault=1)
finally:
SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, None)
if __name__ == '__main__':
gtest_test_utils.Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Verifies that Google Test warns the user when not initialized properly."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import gtest_test_utils
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_uninitialized_test_')
def Assert(condition):
if not condition:
raise AssertionError
def AssertEq(expected, actual):
if expected != actual:
print 'Expected: %s' % (expected,)
print ' Actual: %s' % (actual,)
raise AssertionError
def TestExitCodeAndOutput(command):
"""Runs the given command and verifies its exit code and output."""
# Verifies that 'command' exits with code 1.
p = gtest_test_utils.Subprocess(command)
Assert(p.exited)
AssertEq(1, p.exit_code)
Assert('InitGoogleTest' in p.output)
class GTestUninitializedTest(gtest_test_utils.TestCase):
def testExitCodeAndOutput(self):
TestExitCodeAndOutput(COMMAND)
if __name__ == '__main__':
gtest_test_utils.Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test for Google Test's --gtest_list_tests flag.
A user can ask Google Test to list all tests by specifying the
--gtest_list_tests flag. This script tests such functionality
by invoking gtest_list_tests_unittest_ (a program written with
Google Test) the command line flags.
"""
__author__ = 'phanna@google.com (Patrick Hanna)'
import gtest_test_utils
# Constants.
# The command line flag for enabling/disabling listing all tests.
LIST_TESTS_FLAG = 'gtest_list_tests'
# Path to the gtest_list_tests_unittest_ program.
EXE_PATH = gtest_test_utils.GetTestExecutablePath('gtest_list_tests_unittest_')
# The expected output when running gtest_list_tests_unittest_ with
# --gtest_list_tests
EXPECTED_OUTPUT_NO_FILTER = """FooDeathTest.
Test1
Foo.
Bar1
Bar2
DISABLED_Bar3
Abc.
Xyz
Def
FooBar.
Baz
FooTest.
Test1
DISABLED_Test2
Test3
"""
# The expected output when running gtest_list_tests_unittest_ with
# --gtest_list_tests and --gtest_filter=Foo*.
EXPECTED_OUTPUT_FILTER_FOO = """FooDeathTest.
Test1
Foo.
Bar1
Bar2
DISABLED_Bar3
FooBar.
Baz
FooTest.
Test1
DISABLED_Test2
Test3
"""
# Utilities.
def Run(args):
"""Runs gtest_list_tests_unittest_ and returns the list of tests printed."""
return gtest_test_utils.Subprocess([EXE_PATH] + args,
capture_stderr=False).output
# The unit test.
class GTestListTestsUnitTest(gtest_test_utils.TestCase):
"""Tests using the --gtest_list_tests flag to list all tests."""
def RunAndVerify(self, flag_value, expected_output, other_flag):
"""Runs gtest_list_tests_unittest_ and verifies that it prints
the correct tests.
Args:
flag_value: value of the --gtest_list_tests flag;
None if the flag should not be present.
expected_output: the expected output after running command;
other_flag: a different flag to be passed to command
along with gtest_list_tests;
None if the flag should not be present.
"""
if flag_value is None:
flag = ''
flag_expression = 'not set'
elif flag_value == '0':
flag = '--%s=0' % LIST_TESTS_FLAG
flag_expression = '0'
else:
flag = '--%s' % LIST_TESTS_FLAG
flag_expression = '1'
args = [flag]
if other_flag is not None:
args += [other_flag]
output = Run(args)
msg = ('when %s is %s, the output of "%s" is "%s".' %
(LIST_TESTS_FLAG, flag_expression, ' '.join(args), output))
if expected_output is not None:
self.assert_(output == expected_output, msg)
else:
self.assert_(output != EXPECTED_OUTPUT_NO_FILTER, msg)
def testDefaultBehavior(self):
"""Tests the behavior of the default mode."""
self.RunAndVerify(flag_value=None,
expected_output=None,
other_flag=None)
def testFlag(self):
"""Tests using the --gtest_list_tests flag."""
self.RunAndVerify(flag_value='0',
expected_output=None,
other_flag=None)
self.RunAndVerify(flag_value='1',
expected_output=EXPECTED_OUTPUT_NO_FILTER,
other_flag=None)
def testOverrideNonFilterFlags(self):
"""Tests that --gtest_list_tests overrides the non-filter flags."""
self.RunAndVerify(flag_value='1',
expected_output=EXPECTED_OUTPUT_NO_FILTER,
other_flag='--gtest_break_on_failure')
def testWithFilterFlags(self):
"""Tests that --gtest_list_tests takes into account the
--gtest_filter flag."""
self.RunAndVerify(flag_value='1',
expected_output=EXPECTED_OUTPUT_FILTER_FOO,
other_flag='--gtest_filter=Foo*')
if __name__ == '__main__':
gtest_test_utils.Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests the text output of Google C++ Testing Framework.
SYNOPSIS
gtest_output_test.py --build_dir=BUILD/DIR --gengolden
# where BUILD/DIR contains the built gtest_output_test_ file.
gtest_output_test.py --gengolden
gtest_output_test.py
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import re
import sys
import gtest_test_utils
# The flag for generating the golden file
GENGOLDEN_FLAG = '--gengolden'
CATCH_EXCEPTIONS_ENV_VAR_NAME = 'GTEST_CATCH_EXCEPTIONS'
IS_WINDOWS = os.name == 'nt'
if IS_WINDOWS:
GOLDEN_NAME = 'gtest_output_test_golden_win.txt'
else:
GOLDEN_NAME = 'gtest_output_test_golden_lin.txt'
PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_output_test_')
# At least one command we exercise must not have the
# --gtest_internal_skip_environment_and_ad_hoc_tests flag.
COMMAND_LIST_TESTS = ({}, [PROGRAM_PATH, '--gtest_list_tests'])
COMMAND_WITH_COLOR = ({}, [PROGRAM_PATH, '--gtest_color=yes'])
COMMAND_WITH_TIME = ({}, [PROGRAM_PATH,
'--gtest_print_time',
'--gtest_internal_skip_environment_and_ad_hoc_tests',
'--gtest_filter=FatalFailureTest.*:LoggingTest.*'])
COMMAND_WITH_DISABLED = (
{}, [PROGRAM_PATH,
'--gtest_also_run_disabled_tests',
'--gtest_internal_skip_environment_and_ad_hoc_tests',
'--gtest_filter=*DISABLED_*'])
COMMAND_WITH_SHARDING = (
{'GTEST_SHARD_INDEX': '1', 'GTEST_TOTAL_SHARDS': '2'},
[PROGRAM_PATH,
'--gtest_internal_skip_environment_and_ad_hoc_tests',
'--gtest_filter=PassingTest.*'])
GOLDEN_PATH = os.path.join(gtest_test_utils.GetSourceDir(), GOLDEN_NAME)
def ToUnixLineEnding(s):
"""Changes all Windows/Mac line endings in s to UNIX line endings."""
return s.replace('\r\n', '\n').replace('\r', '\n')
def RemoveLocations(test_output):
"""Removes all file location info from a Google Test program's output.
Args:
test_output: the output of a Google Test program.
Returns:
output with all file location info (in the form of
'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or
'DIRECTORY\\FILE_NAME(LINE_NUMBER): ') replaced by
'FILE_NAME:#: '.
"""
return re.sub(r'.*[/\\](.+)(\:\d+|\(\d+\))\: ', r'\1:#: ', test_output)
def RemoveStackTraceDetails(output):
"""Removes all stack traces from a Google Test program's output."""
# *? means "find the shortest string that matches".
return re.sub(r'Stack trace:(.|\n)*?\n\n',
'Stack trace: (omitted)\n\n', output)
def RemoveStackTraces(output):
"""Removes all traces of stack traces from a Google Test program's output."""
# *? means "find the shortest string that matches".
return re.sub(r'Stack trace:(.|\n)*?\n\n', '', output)
def RemoveTime(output):
"""Removes all time information from a Google Test program's output."""
return re.sub(r'\(\d+ ms', '(? ms', output)
def RemoveTypeInfoDetails(test_output):
"""Removes compiler-specific type info from Google Test program's output.
Args:
test_output: the output of a Google Test program.
Returns:
output with type information normalized to canonical form.
"""
# some compilers output the name of type 'unsigned int' as 'unsigned'
return re.sub(r'unsigned int', 'unsigned', test_output)
def RemoveTestCounts(output):
"""Removes test counts from a Google Test program's output."""
output = re.sub(r'\d+ tests?, listed below',
'? tests, listed below', output)
output = re.sub(r'\d+ FAILED TESTS',
'? FAILED TESTS', output)
output = re.sub(r'\d+ tests? from \d+ test cases?',
'? tests from ? test cases', output)
output = re.sub(r'\d+ tests? from ([a-zA-Z_])',
r'? tests from \1', output)
return re.sub(r'\d+ tests?\.', '? tests.', output)
def RemoveMatchingTests(test_output, pattern):
"""Removes output of specified tests from a Google Test program's output.
This function strips not only the beginning and the end of a test but also
all output in between.
Args:
test_output: A string containing the test output.
pattern: A regex string that matches names of test cases or
tests to remove.
Returns:
Contents of test_output with tests whose names match pattern removed.
"""
test_output = re.sub(
r'.*\[ RUN \] .*%s(.|\n)*?\[( FAILED | OK )\] .*%s.*\n' % (
pattern, pattern),
'',
test_output)
return re.sub(r'.*%s.*\n' % pattern, '', test_output)
def NormalizeOutput(output):
"""Normalizes output (the output of gtest_output_test_.exe)."""
output = ToUnixLineEnding(output)
output = RemoveLocations(output)
output = RemoveStackTraceDetails(output)
output = RemoveTime(output)
return output
def GetShellCommandOutput(env_cmd):
"""Runs a command in a sub-process, and returns its output in a string.
Args:
env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
environment variables to set, and element 1 is a string with
the command and any flags.
Returns:
A string with the command's combined standard and diagnostic output.
"""
# Spawns cmd in a sub-process, and gets its standard I/O file objects.
# Set and save the environment properly.
environ = os.environ.copy()
environ.update(env_cmd[0])
p = gtest_test_utils.Subprocess(env_cmd[1], env=environ)
return p.output
def GetCommandOutput(env_cmd):
"""Runs a command and returns its output with all file location
info stripped off.
Args:
env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
environment variables to set, and element 1 is a string with
the command and any flags.
"""
# Disables exception pop-ups on Windows.
environ, cmdline = env_cmd
environ = dict(environ) # Ensures we are modifying a copy.
environ[CATCH_EXCEPTIONS_ENV_VAR_NAME] = '1'
return NormalizeOutput(GetShellCommandOutput((environ, cmdline)))
def GetOutputOfAllCommands():
"""Returns concatenated output from several representative commands."""
return (GetCommandOutput(COMMAND_WITH_COLOR) +
GetCommandOutput(COMMAND_WITH_TIME) +
GetCommandOutput(COMMAND_WITH_DISABLED) +
GetCommandOutput(COMMAND_WITH_SHARDING))
test_list = GetShellCommandOutput(COMMAND_LIST_TESTS)
SUPPORTS_DEATH_TESTS = 'DeathTest' in test_list
SUPPORTS_TYPED_TESTS = 'TypedTest' in test_list
SUPPORTS_THREADS = 'ExpectFailureWithThreadsTest' in test_list
SUPPORTS_STACK_TRACES = False
CAN_GENERATE_GOLDEN_FILE = (SUPPORTS_DEATH_TESTS and
SUPPORTS_TYPED_TESTS and
(SUPPORTS_THREADS or IS_WINDOWS))
class GTestOutputTest(gtest_test_utils.TestCase):
def RemoveUnsupportedTests(self, test_output):
if not SUPPORTS_DEATH_TESTS:
test_output = RemoveMatchingTests(test_output, 'DeathTest')
if not SUPPORTS_TYPED_TESTS:
test_output = RemoveMatchingTests(test_output, 'TypedTest')
test_output = RemoveMatchingTests(test_output, 'TypedDeathTest')
test_output = RemoveMatchingTests(test_output, 'TypeParamDeathTest')
if not SUPPORTS_THREADS:
test_output = RemoveMatchingTests(test_output,
'ExpectFailureWithThreadsTest')
test_output = RemoveMatchingTests(test_output,
'ScopedFakeTestPartResultReporterTest')
test_output = RemoveMatchingTests(test_output,
'WorksConcurrently')
if not SUPPORTS_STACK_TRACES:
test_output = RemoveStackTraces(test_output)
return test_output
def testOutput(self):
output = GetOutputOfAllCommands()
golden_file = open(GOLDEN_PATH, 'rb')
# A mis-configured source control system can cause \r appear in EOL
# sequences when we read the golden file irrespective of an operating
# system used. Therefore, we need to strip those \r's from newlines
# unconditionally.
golden = ToUnixLineEnding(golden_file.read())
golden_file.close()
# We want the test to pass regardless of certain features being
# supported or not.
# We still have to remove type name specifics in all cases.
normalized_actual = RemoveTypeInfoDetails(output)
normalized_golden = RemoveTypeInfoDetails(golden)
if CAN_GENERATE_GOLDEN_FILE:
self.assertEqual(normalized_golden, normalized_actual)
else:
normalized_actual = RemoveTestCounts(normalized_actual)
normalized_golden = RemoveTestCounts(self.RemoveUnsupportedTests(
normalized_golden))
# This code is very handy when debugging golden file differences:
if os.getenv('DEBUG_GTEST_OUTPUT_TEST'):
open(os.path.join(
gtest_test_utils.GetSourceDir(),
'_gtest_output_test_normalized_actual.txt'), 'wb').write(
normalized_actual)
open(os.path.join(
gtest_test_utils.GetSourceDir(),
'_gtest_output_test_normalized_golden.txt'), 'wb').write(
normalized_golden)
self.assertEqual(normalized_golden, normalized_actual)
if __name__ == '__main__':
if sys.argv[1:] == [GENGOLDEN_FLAG]:
if CAN_GENERATE_GOLDEN_FILE:
output = GetOutputOfAllCommands()
golden_file = open(GOLDEN_PATH, 'wb')
golden_file.write(output)
golden_file.close()
else:
message = (
"""Unable to write a golden file when compiled in an environment
that does not support all the required features (death tests""")
if IS_WINDOWS:
message += (
"""\nand typed tests). Please check that you are using VC++ 8.0 SP1
or higher as your compiler.""")
else:
message += """\ntyped tests, and threads). Please generate the
golden file using a binary built with those features enabled."""
sys.stderr.write(message)
sys.exit(1)
else:
gtest_test_utils.Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2009 Google Inc. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Verifies that test shuffling works."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import gtest_test_utils
# Command to run the gtest_shuffle_test_ program.
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_shuffle_test_')
# The environment variables for test sharding.
TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS'
SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX'
TEST_FILTER = 'A*.A:A*.B:C*'
ALL_TESTS = []
ACTIVE_TESTS = []
FILTERED_TESTS = []
SHARDED_TESTS = []
SHUFFLED_ALL_TESTS = []
SHUFFLED_ACTIVE_TESTS = []
SHUFFLED_FILTERED_TESTS = []
SHUFFLED_SHARDED_TESTS = []
def AlsoRunDisabledTestsFlag():
return '--gtest_also_run_disabled_tests'
def FilterFlag(test_filter):
return '--gtest_filter=%s' % (test_filter,)
def RepeatFlag(n):
return '--gtest_repeat=%s' % (n,)
def ShuffleFlag():
return '--gtest_shuffle'
def RandomSeedFlag(n):
return '--gtest_random_seed=%s' % (n,)
def RunAndReturnOutput(extra_env, args):
"""Runs the test program and returns its output."""
environ_copy = os.environ.copy()
environ_copy.update(extra_env)
return gtest_test_utils.Subprocess([COMMAND] + args, env=environ_copy).output
def GetTestsForAllIterations(extra_env, args):
"""Runs the test program and returns a list of test lists.
Args:
extra_env: a map from environment variables to their values
args: command line flags to pass to gtest_shuffle_test_
Returns:
A list where the i-th element is the list of tests run in the i-th
test iteration.
"""
test_iterations = []
for line in RunAndReturnOutput(extra_env, args).split('\n'):
if line.startswith('----'):
tests = []
test_iterations.append(tests)
elif line.strip():
tests.append(line.strip()) # 'TestCaseName.TestName'
return test_iterations
def GetTestCases(tests):
"""Returns a list of test cases in the given full test names.
Args:
tests: a list of full test names
Returns:
A list of test cases from 'tests', in their original order.
Consecutive duplicates are removed.
"""
test_cases = []
for test in tests:
test_case = test.split('.')[0]
if not test_case in test_cases:
test_cases.append(test_case)
return test_cases
def CalculateTestLists():
"""Calculates the list of tests run under different flags."""
if not ALL_TESTS:
ALL_TESTS.extend(
GetTestsForAllIterations({}, [AlsoRunDisabledTestsFlag()])[0])
if not ACTIVE_TESTS:
ACTIVE_TESTS.extend(GetTestsForAllIterations({}, [])[0])
if not FILTERED_TESTS:
FILTERED_TESTS.extend(
GetTestsForAllIterations({}, [FilterFlag(TEST_FILTER)])[0])
if not SHARDED_TESTS:
SHARDED_TESTS.extend(
GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
SHARD_INDEX_ENV_VAR: '1'},
[])[0])
if not SHUFFLED_ALL_TESTS:
SHUFFLED_ALL_TESTS.extend(GetTestsForAllIterations(
{}, [AlsoRunDisabledTestsFlag(), ShuffleFlag(), RandomSeedFlag(1)])[0])
if not SHUFFLED_ACTIVE_TESTS:
SHUFFLED_ACTIVE_TESTS.extend(GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(1)])[0])
if not SHUFFLED_FILTERED_TESTS:
SHUFFLED_FILTERED_TESTS.extend(GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(1), FilterFlag(TEST_FILTER)])[0])
if not SHUFFLED_SHARDED_TESTS:
SHUFFLED_SHARDED_TESTS.extend(
GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
SHARD_INDEX_ENV_VAR: '1'},
[ShuffleFlag(), RandomSeedFlag(1)])[0])
class GTestShuffleUnitTest(gtest_test_utils.TestCase):
"""Tests test shuffling."""
def setUp(self):
CalculateTestLists()
def testShufflePreservesNumberOfTests(self):
self.assertEqual(len(ALL_TESTS), len(SHUFFLED_ALL_TESTS))
self.assertEqual(len(ACTIVE_TESTS), len(SHUFFLED_ACTIVE_TESTS))
self.assertEqual(len(FILTERED_TESTS), len(SHUFFLED_FILTERED_TESTS))
self.assertEqual(len(SHARDED_TESTS), len(SHUFFLED_SHARDED_TESTS))
def testShuffleChangesTestOrder(self):
self.assert_(SHUFFLED_ALL_TESTS != ALL_TESTS, SHUFFLED_ALL_TESTS)
self.assert_(SHUFFLED_ACTIVE_TESTS != ACTIVE_TESTS, SHUFFLED_ACTIVE_TESTS)
self.assert_(SHUFFLED_FILTERED_TESTS != FILTERED_TESTS,
SHUFFLED_FILTERED_TESTS)
self.assert_(SHUFFLED_SHARDED_TESTS != SHARDED_TESTS,
SHUFFLED_SHARDED_TESTS)
def testShuffleChangesTestCaseOrder(self):
self.assert_(GetTestCases(SHUFFLED_ALL_TESTS) != GetTestCases(ALL_TESTS),
GetTestCases(SHUFFLED_ALL_TESTS))
self.assert_(
GetTestCases(SHUFFLED_ACTIVE_TESTS) != GetTestCases(ACTIVE_TESTS),
GetTestCases(SHUFFLED_ACTIVE_TESTS))
self.assert_(
GetTestCases(SHUFFLED_FILTERED_TESTS) != GetTestCases(FILTERED_TESTS),
GetTestCases(SHUFFLED_FILTERED_TESTS))
self.assert_(
GetTestCases(SHUFFLED_SHARDED_TESTS) != GetTestCases(SHARDED_TESTS),
GetTestCases(SHUFFLED_SHARDED_TESTS))
def testShuffleDoesNotRepeatTest(self):
for test in SHUFFLED_ALL_TESTS:
self.assertEqual(1, SHUFFLED_ALL_TESTS.count(test),
'%s appears more than once' % (test,))
for test in SHUFFLED_ACTIVE_TESTS:
self.assertEqual(1, SHUFFLED_ACTIVE_TESTS.count(test),
'%s appears more than once' % (test,))
for test in SHUFFLED_FILTERED_TESTS:
self.assertEqual(1, SHUFFLED_FILTERED_TESTS.count(test),
'%s appears more than once' % (test,))
for test in SHUFFLED_SHARDED_TESTS:
self.assertEqual(1, SHUFFLED_SHARDED_TESTS.count(test),
'%s appears more than once' % (test,))
def testShuffleDoesNotCreateNewTest(self):
for test in SHUFFLED_ALL_TESTS:
self.assert_(test in ALL_TESTS, '%s is an invalid test' % (test,))
for test in SHUFFLED_ACTIVE_TESTS:
self.assert_(test in ACTIVE_TESTS, '%s is an invalid test' % (test,))
for test in SHUFFLED_FILTERED_TESTS:
self.assert_(test in FILTERED_TESTS, '%s is an invalid test' % (test,))
for test in SHUFFLED_SHARDED_TESTS:
self.assert_(test in SHARDED_TESTS, '%s is an invalid test' % (test,))
def testShuffleIncludesAllTests(self):
for test in ALL_TESTS:
self.assert_(test in SHUFFLED_ALL_TESTS, '%s is missing' % (test,))
for test in ACTIVE_TESTS:
self.assert_(test in SHUFFLED_ACTIVE_TESTS, '%s is missing' % (test,))
for test in FILTERED_TESTS:
self.assert_(test in SHUFFLED_FILTERED_TESTS, '%s is missing' % (test,))
for test in SHARDED_TESTS:
self.assert_(test in SHUFFLED_SHARDED_TESTS, '%s is missing' % (test,))
def testShuffleLeavesDeathTestsAtFront(self):
non_death_test_found = False
for test in SHUFFLED_ACTIVE_TESTS:
if 'DeathTest.' in test:
self.assert_(not non_death_test_found,
'%s appears after a non-death test' % (test,))
else:
non_death_test_found = True
def _VerifyTestCasesDoNotInterleave(self, tests):
test_cases = []
for test in tests:
[test_case, _] = test.split('.')
if test_cases and test_cases[-1] != test_case:
test_cases.append(test_case)
self.assertEqual(1, test_cases.count(test_case),
'Test case %s is not grouped together in %s' %
(test_case, tests))
def testShuffleDoesNotInterleaveTestCases(self):
self._VerifyTestCasesDoNotInterleave(SHUFFLED_ALL_TESTS)
self._VerifyTestCasesDoNotInterleave(SHUFFLED_ACTIVE_TESTS)
self._VerifyTestCasesDoNotInterleave(SHUFFLED_FILTERED_TESTS)
self._VerifyTestCasesDoNotInterleave(SHUFFLED_SHARDED_TESTS)
def testShuffleRestoresOrderAfterEachIteration(self):
# Get the test lists in all 3 iterations, using random seed 1, 2,
# and 3 respectively. Google Test picks a different seed in each
# iteration, and this test depends on the current implementation
# picking successive numbers. This dependency is not ideal, but
# makes the test much easier to write.
[tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (
GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))
# Make sure running the tests with random seed 1 gets the same
# order as in iteration 1 above.
[tests_with_seed1] = GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(1)])
self.assertEqual(tests_in_iteration1, tests_with_seed1)
# Make sure running the tests with random seed 2 gets the same
# order as in iteration 2 above. Success means that Google Test
# correctly restores the test order before re-shuffling at the
# beginning of iteration 2.
[tests_with_seed2] = GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(2)])
self.assertEqual(tests_in_iteration2, tests_with_seed2)
# Make sure running the tests with random seed 3 gets the same
# order as in iteration 3 above. Success means that Google Test
# correctly restores the test order before re-shuffling at the
# beginning of iteration 3.
[tests_with_seed3] = GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(3)])
self.assertEqual(tests_in_iteration3, tests_with_seed3)
def testShuffleGeneratesNewOrderInEachIteration(self):
[tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (
GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))
self.assert_(tests_in_iteration1 != tests_in_iteration2,
tests_in_iteration1)
self.assert_(tests_in_iteration1 != tests_in_iteration3,
tests_in_iteration1)
self.assert_(tests_in_iteration2 != tests_in_iteration3,
tests_in_iteration2)
def testShuffleShardedTestsPreservesPartition(self):
# If we run M tests on N shards, the same M tests should be run in
# total, regardless of the random seeds used by the shards.
[tests1] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
SHARD_INDEX_ENV_VAR: '0'},
[ShuffleFlag(), RandomSeedFlag(1)])
[tests2] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
SHARD_INDEX_ENV_VAR: '1'},
[ShuffleFlag(), RandomSeedFlag(20)])
[tests3] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
SHARD_INDEX_ENV_VAR: '2'},
[ShuffleFlag(), RandomSeedFlag(25)])
sorted_sharded_tests = tests1 + tests2 + tests3
sorted_sharded_tests.sort()
sorted_active_tests = []
sorted_active_tests.extend(ACTIVE_TESTS)
sorted_active_tests.sort()
self.assertEqual(sorted_active_tests, sorted_sharded_tests)
if __name__ == '__main__':
gtest_test_utils.Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2009, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests Google Test's throw-on-failure mode with exceptions disabled.
This script invokes gtest_throw_on_failure_test_ (a program written with
Google Test) with different environments and command line flags.
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import gtest_test_utils
# Constants.
# The command line flag for enabling/disabling the throw-on-failure mode.
THROW_ON_FAILURE = 'gtest_throw_on_failure'
# Path to the gtest_throw_on_failure_test_ program, compiled with
# exceptions disabled.
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
'gtest_throw_on_failure_test_')
# Utilities.
def SetEnvVar(env_var, value):
"""Sets an environment variable to a given value; unsets it when the
given value is None.
"""
env_var = env_var.upper()
if value is not None:
os.environ[env_var] = value
elif env_var in os.environ:
del os.environ[env_var]
def Run(command):
"""Runs a command; returns True/False if its exit code is/isn't 0."""
print 'Running "%s". . .' % ' '.join(command)
p = gtest_test_utils.Subprocess(command)
return p.exited and p.exit_code == 0
# The tests. TODO(wan@google.com): refactor the class to share common
# logic with code in gtest_break_on_failure_unittest.py.
class ThrowOnFailureTest(gtest_test_utils.TestCase):
"""Tests the throw-on-failure mode."""
def RunAndVerify(self, env_var_value, flag_value, should_fail):
"""Runs gtest_throw_on_failure_test_ and verifies that it does
(or does not) exit with a non-zero code.
Args:
env_var_value: value of the GTEST_BREAK_ON_FAILURE environment
variable; None if the variable should be unset.
flag_value: value of the --gtest_break_on_failure flag;
None if the flag should not be present.
should_fail: True iff the program is expected to fail.
"""
SetEnvVar(THROW_ON_FAILURE, env_var_value)
if env_var_value is None:
env_var_value_msg = ' is not set'
else:
env_var_value_msg = '=' + env_var_value
if flag_value is None:
flag = ''
elif flag_value == '0':
flag = '--%s=0' % THROW_ON_FAILURE
else:
flag = '--%s' % THROW_ON_FAILURE
command = [EXE_PATH]
if flag:
command.append(flag)
if should_fail:
should_or_not = 'should'
else:
should_or_not = 'should not'
failed = not Run(command)
SetEnvVar(THROW_ON_FAILURE, None)
msg = ('when %s%s, an assertion failure in "%s" %s cause a non-zero '
'exit code.' %
(THROW_ON_FAILURE, env_var_value_msg, ' '.join(command),
should_or_not))
self.assert_(failed == should_fail, msg)
def testDefaultBehavior(self):
"""Tests the behavior of the default mode."""
self.RunAndVerify(env_var_value=None, flag_value=None, should_fail=False)
def testThrowOnFailureEnvVar(self):
"""Tests using the GTEST_THROW_ON_FAILURE environment variable."""
self.RunAndVerify(env_var_value='0',
flag_value=None,
should_fail=False)
self.RunAndVerify(env_var_value='1',
flag_value=None,
should_fail=True)
def testThrowOnFailureFlag(self):
"""Tests using the --gtest_throw_on_failure flag."""
self.RunAndVerify(env_var_value=None,
flag_value='0',
should_fail=False)
self.RunAndVerify(env_var_value=None,
flag_value='1',
should_fail=True)
def testThrowOnFailureFlagOverridesEnvVar(self):
"""Tests that --gtest_throw_on_failure overrides GTEST_THROW_ON_FAILURE."""
self.RunAndVerify(env_var_value='0',
flag_value='0',
should_fail=False)
self.RunAndVerify(env_var_value='0',
flag_value='1',
should_fail=True)
self.RunAndVerify(env_var_value='1',
flag_value='0',
should_fail=False)
self.RunAndVerify(env_var_value='1',
flag_value='1',
should_fail=True)
if __name__ == '__main__':
gtest_test_utils.Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2005 Google Inc. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test for Google Test test filters.
A user can specify which test(s) in a Google Test program to run via either
the GTEST_FILTER environment variable or the --gtest_filter flag.
This script tests such functionality by invoking
gtest_filter_unittest_ (a program written with Google Test) with different
environments and command line flags.
Note that test sharding may also influence which tests are filtered. Therefore,
we test that here also.
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import re
import sets
import sys
import gtest_test_utils
# Constants.
# Checks if this platform can pass empty environment variables to child
# processes. We set an env variable to an empty string and invoke a python
# script in a subprocess to print whether the variable is STILL in
# os.environ. We then use 'eval' to parse the child's output so that an
# exception is thrown if the input is anything other than 'True' nor 'False'.
os.environ['EMPTY_VAR'] = ''
child = gtest_test_utils.Subprocess(
[sys.executable, '-c', 'import os; print \'EMPTY_VAR\' in os.environ'])
CAN_PASS_EMPTY_ENV = eval(child.output)
# Check if this platform can unset environment variables in child processes.
# We set an env variable to a non-empty string, unset it, and invoke
# a python script in a subprocess to print whether the variable
# is NO LONGER in os.environ.
# We use 'eval' to parse the child's output so that an exception
# is thrown if the input is neither 'True' nor 'False'.
os.environ['UNSET_VAR'] = 'X'
del os.environ['UNSET_VAR']
child = gtest_test_utils.Subprocess(
[sys.executable, '-c', 'import os; print \'UNSET_VAR\' not in os.environ'])
CAN_UNSET_ENV = eval(child.output)
# Checks if we should test with an empty filter. This doesn't
# make sense on platforms that cannot pass empty env variables (Win32)
# and on platforms that cannot unset variables (since we cannot tell
# the difference between "" and NULL -- Borland and Solaris < 5.10)
CAN_TEST_EMPTY_FILTER = (CAN_PASS_EMPTY_ENV and CAN_UNSET_ENV)
# The environment variable for specifying the test filters.
FILTER_ENV_VAR = 'GTEST_FILTER'
# The environment variables for test sharding.
TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS'
SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX'
SHARD_STATUS_FILE_ENV_VAR = 'GTEST_SHARD_STATUS_FILE'
# The command line flag for specifying the test filters.
FILTER_FLAG = 'gtest_filter'
# The command line flag for including disabled tests.
ALSO_RUN_DISABED_TESTS_FLAG = 'gtest_also_run_disabled_tests'
# Command to run the gtest_filter_unittest_ program.
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_filter_unittest_')
# Regex for determining whether parameterized tests are enabled in the binary.
PARAM_TEST_REGEX = re.compile(r'/ParamTest')
# Regex for parsing test case names from Google Test's output.
TEST_CASE_REGEX = re.compile(r'^\[\-+\] \d+ tests? from (\w+(/\w+)?)')
# Regex for parsing test names from Google Test's output.
TEST_REGEX = re.compile(r'^\[\s*RUN\s*\].*\.(\w+(/\w+)?)')
# The command line flag to tell Google Test to output the list of tests it
# will run.
LIST_TESTS_FLAG = '--gtest_list_tests'
# Indicates whether Google Test supports death tests.
SUPPORTS_DEATH_TESTS = 'HasDeathTest' in gtest_test_utils.Subprocess(
[COMMAND, LIST_TESTS_FLAG]).output
# Full names of all tests in gtest_filter_unittests_.
PARAM_TESTS = [
'SeqP/ParamTest.TestX/0',
'SeqP/ParamTest.TestX/1',
'SeqP/ParamTest.TestY/0',
'SeqP/ParamTest.TestY/1',
'SeqQ/ParamTest.TestX/0',
'SeqQ/ParamTest.TestX/1',
'SeqQ/ParamTest.TestY/0',
'SeqQ/ParamTest.TestY/1',
]
DISABLED_TESTS = [
'BarTest.DISABLED_TestFour',
'BarTest.DISABLED_TestFive',
'BazTest.DISABLED_TestC',
'DISABLED_FoobarTest.Test1',
'DISABLED_FoobarTest.DISABLED_Test2',
'DISABLED_FoobarbazTest.TestA',
]
if SUPPORTS_DEATH_TESTS:
DEATH_TESTS = [
'HasDeathTest.Test1',
'HasDeathTest.Test2',
]
else:
DEATH_TESTS = []
# All the non-disabled tests.
ACTIVE_TESTS = [
'FooTest.Abc',
'FooTest.Xyz',
'BarTest.TestOne',
'BarTest.TestTwo',
'BarTest.TestThree',
'BazTest.TestOne',
'BazTest.TestA',
'BazTest.TestB',
] + DEATH_TESTS + PARAM_TESTS
param_tests_present = None
# Utilities.
environ = os.environ.copy()
def SetEnvVar(env_var, value):
"""Sets the env variable to 'value'; unsets it when 'value' is None."""
if value is not None:
environ[env_var] = value
elif env_var in environ:
del environ[env_var]
def RunAndReturnOutput(args = None):
"""Runs the test program and returns its output."""
return gtest_test_utils.Subprocess([COMMAND] + (args or []),
env=environ).output
def RunAndExtractTestList(args = None):
"""Runs the test program and returns its exit code and a list of tests run."""
p = gtest_test_utils.Subprocess([COMMAND] + (args or []), env=environ)
tests_run = []
test_case = ''
test = ''
for line in p.output.split('\n'):
match = TEST_CASE_REGEX.match(line)
if match is not None:
test_case = match.group(1)
else:
match = TEST_REGEX.match(line)
if match is not None:
test = match.group(1)
tests_run.append(test_case + '.' + test)
return (tests_run, p.exit_code)
def InvokeWithModifiedEnv(extra_env, function, *args, **kwargs):
"""Runs the given function and arguments in a modified environment."""
try:
original_env = environ.copy()
environ.update(extra_env)
return function(*args, **kwargs)
finally:
environ.clear()
environ.update(original_env)
def RunWithSharding(total_shards, shard_index, command):
"""Runs a test program shard and returns exit code and a list of tests run."""
extra_env = {SHARD_INDEX_ENV_VAR: str(shard_index),
TOTAL_SHARDS_ENV_VAR: str(total_shards)}
return InvokeWithModifiedEnv(extra_env, RunAndExtractTestList, command)
# The unit test.
class GTestFilterUnitTest(gtest_test_utils.TestCase):
"""Tests the env variable or the command line flag to filter tests."""
# Utilities.
def AssertSetEqual(self, lhs, rhs):
"""Asserts that two sets are equal."""
for elem in lhs:
self.assert_(elem in rhs, '%s in %s' % (elem, rhs))
for elem in rhs:
self.assert_(elem in lhs, '%s in %s' % (elem, lhs))
def AssertPartitionIsValid(self, set_var, list_of_sets):
"""Asserts that list_of_sets is a valid partition of set_var."""
full_partition = []
for slice_var in list_of_sets:
full_partition.extend(slice_var)
self.assertEqual(len(set_var), len(full_partition))
self.assertEqual(sets.Set(set_var), sets.Set(full_partition))
def AdjustForParameterizedTests(self, tests_to_run):
"""Adjust tests_to_run in case value parameterized tests are disabled."""
global param_tests_present
if not param_tests_present:
return list(sets.Set(tests_to_run) - sets.Set(PARAM_TESTS))
else:
return tests_to_run
def RunAndVerify(self, gtest_filter, tests_to_run):
"""Checks that the binary runs correct set of tests for a given filter."""
tests_to_run = self.AdjustForParameterizedTests(tests_to_run)
# First, tests using the environment variable.
# Windows removes empty variables from the environment when passing it
# to a new process. This means it is impossible to pass an empty filter
# into a process using the environment variable. However, we can still
# test the case when the variable is not supplied (i.e., gtest_filter is
# None).
# pylint: disable-msg=C6403
if CAN_TEST_EMPTY_FILTER or gtest_filter != '':
SetEnvVar(FILTER_ENV_VAR, gtest_filter)
tests_run = RunAndExtractTestList()[0]
SetEnvVar(FILTER_ENV_VAR, None)
self.AssertSetEqual(tests_run, tests_to_run)
# pylint: enable-msg=C6403
# Next, tests using the command line flag.
if gtest_filter is None:
args = []
else:
args = ['--%s=%s' % (FILTER_FLAG, gtest_filter)]
tests_run = RunAndExtractTestList(args)[0]
self.AssertSetEqual(tests_run, tests_to_run)
def RunAndVerifyWithSharding(self, gtest_filter, total_shards, tests_to_run,
args=None, check_exit_0=False):
"""Checks that binary runs correct tests for the given filter and shard.
Runs all shards of gtest_filter_unittest_ with the given filter, and
verifies that the right set of tests were run. The union of tests run
on each shard should be identical to tests_to_run, without duplicates.
Args:
gtest_filter: A filter to apply to the tests.
total_shards: A total number of shards to split test run into.
tests_to_run: A set of tests expected to run.
args : Arguments to pass to the to the test binary.
check_exit_0: When set to a true value, make sure that all shards
return 0.
"""
tests_to_run = self.AdjustForParameterizedTests(tests_to_run)
# Windows removes empty variables from the environment when passing it
# to a new process. This means it is impossible to pass an empty filter
# into a process using the environment variable. However, we can still
# test the case when the variable is not supplied (i.e., gtest_filter is
# None).
# pylint: disable-msg=C6403
if CAN_TEST_EMPTY_FILTER or gtest_filter != '':
SetEnvVar(FILTER_ENV_VAR, gtest_filter)
partition = []
for i in range(0, total_shards):
(tests_run, exit_code) = RunWithSharding(total_shards, i, args)
if check_exit_0:
self.assertEqual(0, exit_code)
partition.append(tests_run)
self.AssertPartitionIsValid(tests_to_run, partition)
SetEnvVar(FILTER_ENV_VAR, None)
# pylint: enable-msg=C6403
def RunAndVerifyAllowingDisabled(self, gtest_filter, tests_to_run):
"""Checks that the binary runs correct set of tests for the given filter.
Runs gtest_filter_unittest_ with the given filter, and enables
disabled tests. Verifies that the right set of tests were run.
Args:
gtest_filter: A filter to apply to the tests.
tests_to_run: A set of tests expected to run.
"""
tests_to_run = self.AdjustForParameterizedTests(tests_to_run)
# Construct the command line.
args = ['--%s' % ALSO_RUN_DISABED_TESTS_FLAG]
if gtest_filter is not None:
args.append('--%s=%s' % (FILTER_FLAG, gtest_filter))
tests_run = RunAndExtractTestList(args)[0]
self.AssertSetEqual(tests_run, tests_to_run)
def setUp(self):
"""Sets up test case.
Determines whether value-parameterized tests are enabled in the binary and
sets the flags accordingly.
"""
global param_tests_present
if param_tests_present is None:
param_tests_present = PARAM_TEST_REGEX.search(
RunAndReturnOutput()) is not None
def testDefaultBehavior(self):
"""Tests the behavior of not specifying the filter."""
self.RunAndVerify(None, ACTIVE_TESTS)
def testDefaultBehaviorWithShards(self):
"""Tests the behavior without the filter, with sharding enabled."""
self.RunAndVerifyWithSharding(None, 1, ACTIVE_TESTS)
self.RunAndVerifyWithSharding(None, 2, ACTIVE_TESTS)
self.RunAndVerifyWithSharding(None, len(ACTIVE_TESTS) - 1, ACTIVE_TESTS)
self.RunAndVerifyWithSharding(None, len(ACTIVE_TESTS), ACTIVE_TESTS)
self.RunAndVerifyWithSharding(None, len(ACTIVE_TESTS) + 1, ACTIVE_TESTS)
def testEmptyFilter(self):
"""Tests an empty filter."""
self.RunAndVerify('', [])
self.RunAndVerifyWithSharding('', 1, [])
self.RunAndVerifyWithSharding('', 2, [])
def testBadFilter(self):
"""Tests a filter that matches nothing."""
self.RunAndVerify('BadFilter', [])
self.RunAndVerifyAllowingDisabled('BadFilter', [])
def testFullName(self):
"""Tests filtering by full name."""
self.RunAndVerify('FooTest.Xyz', ['FooTest.Xyz'])
self.RunAndVerifyAllowingDisabled('FooTest.Xyz', ['FooTest.Xyz'])
self.RunAndVerifyWithSharding('FooTest.Xyz', 5, ['FooTest.Xyz'])
def testUniversalFilters(self):
"""Tests filters that match everything."""
self.RunAndVerify('*', ACTIVE_TESTS)
self.RunAndVerify('*.*', ACTIVE_TESTS)
self.RunAndVerifyWithSharding('*.*', len(ACTIVE_TESTS) - 3, ACTIVE_TESTS)
self.RunAndVerifyAllowingDisabled('*', ACTIVE_TESTS + DISABLED_TESTS)
self.RunAndVerifyAllowingDisabled('*.*', ACTIVE_TESTS + DISABLED_TESTS)
def testFilterByTestCase(self):
"""Tests filtering by test case name."""
self.RunAndVerify('FooTest.*', ['FooTest.Abc', 'FooTest.Xyz'])
BAZ_TESTS = ['BazTest.TestOne', 'BazTest.TestA', 'BazTest.TestB']
self.RunAndVerify('BazTest.*', BAZ_TESTS)
self.RunAndVerifyAllowingDisabled('BazTest.*',
BAZ_TESTS + ['BazTest.DISABLED_TestC'])
def testFilterByTest(self):
"""Tests filtering by test name."""
self.RunAndVerify('*.TestOne', ['BarTest.TestOne', 'BazTest.TestOne'])
def testFilterDisabledTests(self):
"""Select only the disabled tests to run."""
self.RunAndVerify('DISABLED_FoobarTest.Test1', [])
self.RunAndVerifyAllowingDisabled('DISABLED_FoobarTest.Test1',
['DISABLED_FoobarTest.Test1'])
self.RunAndVerify('*DISABLED_*', [])
self.RunAndVerifyAllowingDisabled('*DISABLED_*', DISABLED_TESTS)
self.RunAndVerify('*.DISABLED_*', [])
self.RunAndVerifyAllowingDisabled('*.DISABLED_*', [
'BarTest.DISABLED_TestFour',
'BarTest.DISABLED_TestFive',
'BazTest.DISABLED_TestC',
'DISABLED_FoobarTest.DISABLED_Test2',
])
self.RunAndVerify('DISABLED_*', [])
self.RunAndVerifyAllowingDisabled('DISABLED_*', [
'DISABLED_FoobarTest.Test1',
'DISABLED_FoobarTest.DISABLED_Test2',
'DISABLED_FoobarbazTest.TestA',
])
def testWildcardInTestCaseName(self):
"""Tests using wildcard in the test case name."""
self.RunAndVerify('*a*.*', [
'BarTest.TestOne',
'BarTest.TestTwo',
'BarTest.TestThree',
'BazTest.TestOne',
'BazTest.TestA',
'BazTest.TestB', ] + DEATH_TESTS + PARAM_TESTS)
def testWildcardInTestName(self):
"""Tests using wildcard in the test name."""
self.RunAndVerify('*.*A*', ['FooTest.Abc', 'BazTest.TestA'])
def testFilterWithoutDot(self):
"""Tests a filter that has no '.' in it."""
self.RunAndVerify('*z*', [
'FooTest.Xyz',
'BazTest.TestOne',
'BazTest.TestA',
'BazTest.TestB',
])
def testTwoPatterns(self):
"""Tests filters that consist of two patterns."""
self.RunAndVerify('Foo*.*:*A*', [
'FooTest.Abc',
'FooTest.Xyz',
'BazTest.TestA',
])
# An empty pattern + a non-empty one
self.RunAndVerify(':*A*', ['FooTest.Abc', 'BazTest.TestA'])
def testThreePatterns(self):
"""Tests filters that consist of three patterns."""
self.RunAndVerify('*oo*:*A*:*One', [
'FooTest.Abc',
'FooTest.Xyz',
'BarTest.TestOne',
'BazTest.TestOne',
'BazTest.TestA',
])
# The 2nd pattern is empty.
self.RunAndVerify('*oo*::*One', [
'FooTest.Abc',
'FooTest.Xyz',
'BarTest.TestOne',
'BazTest.TestOne',
])
# The last 2 patterns are empty.
self.RunAndVerify('*oo*::', [
'FooTest.Abc',
'FooTest.Xyz',
])
def testNegativeFilters(self):
self.RunAndVerify('*-BazTest.TestOne', [
'FooTest.Abc',
'FooTest.Xyz',
'BarTest.TestOne',
'BarTest.TestTwo',
'BarTest.TestThree',
'BazTest.TestA',
'BazTest.TestB',
] + DEATH_TESTS + PARAM_TESTS)
self.RunAndVerify('*-FooTest.Abc:BazTest.*', [
'FooTest.Xyz',
'BarTest.TestOne',
'BarTest.TestTwo',
'BarTest.TestThree',
] + DEATH_TESTS + PARAM_TESTS)
self.RunAndVerify('BarTest.*-BarTest.TestOne', [
'BarTest.TestTwo',
'BarTest.TestThree',
])
# Tests without leading '*'.
self.RunAndVerify('-FooTest.Abc:FooTest.Xyz:BazTest.*', [
'BarTest.TestOne',
'BarTest.TestTwo',
'BarTest.TestThree',
] + DEATH_TESTS + PARAM_TESTS)
# Value parameterized tests.
self.RunAndVerify('*/*', PARAM_TESTS)
# Value parameterized tests filtering by the sequence name.
self.RunAndVerify('SeqP/*', [
'SeqP/ParamTest.TestX/0',
'SeqP/ParamTest.TestX/1',
'SeqP/ParamTest.TestY/0',
'SeqP/ParamTest.TestY/1',
])
# Value parameterized tests filtering by the test name.
self.RunAndVerify('*/0', [
'SeqP/ParamTest.TestX/0',
'SeqP/ParamTest.TestY/0',
'SeqQ/ParamTest.TestX/0',
'SeqQ/ParamTest.TestY/0',
])
def testFlagOverridesEnvVar(self):
"""Tests that the filter flag overrides the filtering env. variable."""
SetEnvVar(FILTER_ENV_VAR, 'Foo*')
args = ['--%s=%s' % (FILTER_FLAG, '*One')]
tests_run = RunAndExtractTestList(args)[0]
SetEnvVar(FILTER_ENV_VAR, None)
self.AssertSetEqual(tests_run, ['BarTest.TestOne', 'BazTest.TestOne'])
def testShardStatusFileIsCreated(self):
"""Tests that the shard file is created if specified in the environment."""
shard_status_file = os.path.join(gtest_test_utils.GetTempDir(),
'shard_status_file')
self.assert_(not os.path.exists(shard_status_file))
extra_env = {SHARD_STATUS_FILE_ENV_VAR: shard_status_file}
try:
InvokeWithModifiedEnv(extra_env, RunAndReturnOutput)
finally:
self.assert_(os.path.exists(shard_status_file))
os.remove(shard_status_file)
def testShardStatusFileIsCreatedWithListTests(self):
"""Tests that the shard file is created with the "list_tests" flag."""
shard_status_file = os.path.join(gtest_test_utils.GetTempDir(),
'shard_status_file2')
self.assert_(not os.path.exists(shard_status_file))
extra_env = {SHARD_STATUS_FILE_ENV_VAR: shard_status_file}
try:
output = InvokeWithModifiedEnv(extra_env,
RunAndReturnOutput,
[LIST_TESTS_FLAG])
finally:
# This assertion ensures that Google Test enumerated the tests as
# opposed to running them.
self.assert_('[==========]' not in output,
'Unexpected output during test enumeration.\n'
'Please ensure that LIST_TESTS_FLAG is assigned the\n'
'correct flag value for listing Google Test tests.')
self.assert_(os.path.exists(shard_status_file))
os.remove(shard_status_file)
if SUPPORTS_DEATH_TESTS:
def testShardingWorksWithDeathTests(self):
"""Tests integration with death tests and sharding."""
gtest_filter = 'HasDeathTest.*:SeqP/*'
expected_tests = [
'HasDeathTest.Test1',
'HasDeathTest.Test2',
'SeqP/ParamTest.TestX/0',
'SeqP/ParamTest.TestX/1',
'SeqP/ParamTest.TestY/0',
'SeqP/ParamTest.TestY/1',
]
for flag in ['--gtest_death_test_style=threadsafe',
'--gtest_death_test_style=fast']:
self.RunAndVerifyWithSharding(gtest_filter, 3, expected_tests,
check_exit_0=True, args=[flag])
self.RunAndVerifyWithSharding(gtest_filter, 5, expected_tests,
check_exit_0=True, args=[flag])
if __name__ == '__main__':
gtest_test_utils.Main()
| Python |
# Copyright 2008 Google Inc. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Provides facilities for running SCons-built Google Test/Mock tests."""
import optparse
import os
import re
import sets
import sys
try:
# subrocess module is a preferable way to invoke subprocesses but it may
# not be available on MacOS X 10.4.
# Suppresses the 'Import not at the top of the file' lint complaint.
# pylint: disable-msg=C6204
import subprocess
except ImportError:
subprocess = None
HELP_MSG = """Runs the specified tests for %(proj)s.
SYNOPSIS
run_tests.py [OPTION]... [BUILD_DIR]... [TEST]...
DESCRIPTION
Runs the specified tests (either binary or Python), and prints a
summary of the results. BUILD_DIRS will be used to search for the
binaries. If no TESTs are specified, all binary tests found in
BUILD_DIRs and all Python tests found in the directory test/ (in the
%(proj)s root) are run.
TEST is a name of either a binary or a Python test. A binary test is
an executable file named *_test or *_unittest (with the .exe
extension on Windows) A Python test is a script named *_test.py or
*_unittest.py.
OPTIONS
-h, --help
Print this help message.
-c CONFIGURATIONS
Specify build directories via build configurations.
CONFIGURATIONS is either a comma-separated list of build
configurations or 'all'. Each configuration is equivalent to
adding 'scons/build/<configuration>/%(proj)s/scons' to BUILD_DIRs.
Specifying -c=all is equivalent to providing all directories
listed in KNOWN BUILD DIRECTORIES section below.
-a
Equivalent to -c=all
-b
Equivalent to -c=all with the exception that the script will not
fail if some of the KNOWN BUILD DIRECTORIES do not exists; the
script will simply not run the tests there. 'b' stands for
'built directories'.
RETURN VALUE
Returns 0 if all tests are successful; otherwise returns 1.
EXAMPLES
run_tests.py
Runs all tests for the default build configuration.
run_tests.py -a
Runs all tests with binaries in KNOWN BUILD DIRECTORIES.
run_tests.py -b
Runs all tests in KNOWN BUILD DIRECTORIES that have been
built.
run_tests.py foo/
Runs all tests in the foo/ directory and all Python tests in
the directory test. The Python tests are instructed to look
for binaries in foo/.
run_tests.py bar_test.exe test/baz_test.exe foo/ bar/
Runs foo/bar_test.exe, bar/bar_test.exe, foo/baz_test.exe, and
bar/baz_test.exe.
run_tests.py foo bar test/foo_test.py
Runs test/foo_test.py twice instructing it to look for its
test binaries in the directories foo and bar,
correspondingly.
KNOWN BUILD DIRECTORIES
run_tests.py knows about directories where the SCons build script
deposits its products. These are the directories where run_tests.py
will be looking for its binaries. Currently, %(proj)s's SConstruct file
defines them as follows (the default build directory is the first one
listed in each group):
On Windows:
<%(proj)s root>/scons/build/win-dbg8/%(proj)s/scons/
<%(proj)s root>/scons/build/win-opt8/%(proj)s/scons/
On Mac:
<%(proj)s root>/scons/build/mac-dbg/%(proj)s/scons/
<%(proj)s root>/scons/build/mac-opt/%(proj)s/scons/
On other platforms:
<%(proj)s root>/scons/build/dbg/%(proj)s/scons/
<%(proj)s root>/scons/build/opt/%(proj)s/scons/"""
IS_WINDOWS = os.name == 'nt'
IS_MAC = os.name == 'posix' and os.uname()[0] == 'Darwin'
IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0]
# Definition of CONFIGS must match that of the build directory names in the
# SConstruct script. The first list item is the default build configuration.
if IS_WINDOWS:
CONFIGS = ('win-dbg8', 'win-opt8')
elif IS_MAC:
CONFIGS = ('mac-dbg', 'mac-opt')
else:
CONFIGS = ('dbg', 'opt')
if IS_WINDOWS or IS_CYGWIN:
PYTHON_TEST_REGEX = re.compile(r'_(unit)?test\.py$', re.IGNORECASE)
BINARY_TEST_REGEX = re.compile(r'_(unit)?test(\.exe)?$', re.IGNORECASE)
BINARY_TEST_SEARCH_REGEX = re.compile(r'_(unit)?test\.exe$', re.IGNORECASE)
else:
PYTHON_TEST_REGEX = re.compile(r'_(unit)?test\.py$')
BINARY_TEST_REGEX = re.compile(r'_(unit)?test$')
BINARY_TEST_SEARCH_REGEX = BINARY_TEST_REGEX
def _GetGtestBuildDir(injected_os, script_dir, config):
"""Calculates path to the Google Test SCons build directory."""
return injected_os.path.normpath(injected_os.path.join(script_dir,
'scons/build',
config,
'gtest/scons'))
def _GetConfigFromBuildDir(build_dir):
"""Extracts the configuration name from the build directory."""
# We don't want to depend on build_dir containing the correct path
# separators.
m = re.match(r'.*[\\/]([^\\/]+)[\\/][^\\/]+[\\/]scons[\\/]?$', build_dir)
if m:
return m.group(1)
else:
print >>sys.stderr, ('%s is an invalid build directory that does not '
'correspond to any configuration.' % (build_dir,))
return ''
# All paths in this script are either absolute or relative to the current
# working directory, unless otherwise specified.
class TestRunner(object):
"""Provides facilities for running Python and binary tests for Google Test."""
def __init__(self,
script_dir,
build_dir_var_name='BUILD_DIR',
injected_os=os,
injected_subprocess=subprocess,
injected_build_dir_finder=_GetGtestBuildDir):
"""Initializes a TestRunner instance.
Args:
script_dir: File path to the calling script.
build_dir_var_name: Name of the env variable used to pass the
the build directory path to the invoked
tests.
injected_os: standard os module or a mock/stub for
testing.
injected_subprocess: standard subprocess module or a mock/stub
for testing
injected_build_dir_finder: function that determines the path to
the build directory.
"""
self.os = injected_os
self.subprocess = injected_subprocess
self.build_dir_finder = injected_build_dir_finder
self.build_dir_var_name = build_dir_var_name
self.script_dir = script_dir
def _GetBuildDirForConfig(self, config):
"""Returns the build directory for a given configuration."""
return self.build_dir_finder(self.os, self.script_dir, config)
def _Run(self, args):
"""Runs the executable with given args (args[0] is the executable name).
Args:
args: Command line arguments for the process.
Returns:
Process's exit code if it exits normally, or -signal if the process is
killed by a signal.
"""
if self.subprocess:
return self.subprocess.Popen(args).wait()
else:
return self.os.spawnv(self.os.P_WAIT, args[0], args)
def _RunBinaryTest(self, test):
"""Runs the binary test given its path.
Args:
test: Path to the test binary.
Returns:
Process's exit code if it exits normally, or -signal if the process is
killed by a signal.
"""
return self._Run([test])
def _RunPythonTest(self, test, build_dir):
"""Runs the Python test script with the specified build directory.
Args:
test: Path to the test's Python script.
build_dir: Path to the directory where the test binary is to be found.
Returns:
Process's exit code if it exits normally, or -signal if the process is
killed by a signal.
"""
old_build_dir = self.os.environ.get(self.build_dir_var_name)
try:
self.os.environ[self.build_dir_var_name] = build_dir
# If this script is run on a Windows machine that has no association
# between the .py extension and a python interpreter, simply passing
# the script name into subprocess.Popen/os.spawn will not work.
print 'Running %s . . .' % (test,)
return self._Run([sys.executable, test])
finally:
if old_build_dir is None:
del self.os.environ[self.build_dir_var_name]
else:
self.os.environ[self.build_dir_var_name] = old_build_dir
def _FindFilesByRegex(self, directory, regex):
"""Returns files in a directory whose names match a regular expression.
Args:
directory: Path to the directory to search for files.
regex: Regular expression to filter file names.
Returns:
The list of the paths to the files in the directory.
"""
return [self.os.path.join(directory, file_name)
for file_name in self.os.listdir(directory)
if re.search(regex, file_name)]
# TODO(vladl@google.com): Implement parsing of scons/SConscript to run all
# tests defined there when no tests are specified.
# TODO(vladl@google.com): Update the docstring after the code is changed to
# try to test all builds defined in scons/SConscript.
def GetTestsToRun(self,
args,
named_configurations,
built_configurations,
available_configurations=CONFIGS,
python_tests_to_skip=None):
"""Determines what tests should be run.
Args:
args: The list of non-option arguments from the command line.
named_configurations: The list of configurations specified via -c or -a.
built_configurations: True if -b has been specified.
available_configurations: a list of configurations available on the
current platform, injectable for testing.
python_tests_to_skip: a collection of (configuration, python test name)s
that need to be skipped.
Returns:
A tuple with 2 elements: the list of Python tests to run and the list of
binary tests to run.
"""
if named_configurations == 'all':
named_configurations = ','.join(available_configurations)
normalized_args = [self.os.path.normpath(arg) for arg in args]
# A final list of build directories which will be searched for the test
# binaries. First, add directories specified directly on the command
# line.
build_dirs = filter(self.os.path.isdir, normalized_args)
# Adds build directories specified via their build configurations using
# the -c or -a options.
if named_configurations:
build_dirs += [self._GetBuildDirForConfig(config)
for config in named_configurations.split(',')]
# Adds KNOWN BUILD DIRECTORIES if -b is specified.
if built_configurations:
build_dirs += [self._GetBuildDirForConfig(config)
for config in available_configurations
if self.os.path.isdir(self._GetBuildDirForConfig(config))]
# If no directories were specified either via -a, -b, -c, or directly, use
# the default configuration.
elif not build_dirs:
build_dirs = [self._GetBuildDirForConfig(available_configurations[0])]
# Makes sure there are no duplications.
build_dirs = sets.Set(build_dirs)
errors_found = False
listed_python_tests = [] # All Python tests listed on the command line.
listed_binary_tests = [] # All binary tests listed on the command line.
test_dir = self.os.path.normpath(self.os.path.join(self.script_dir, 'test'))
# Sifts through non-directory arguments fishing for any Python or binary
# tests and detecting errors.
for argument in sets.Set(normalized_args) - build_dirs:
if re.search(PYTHON_TEST_REGEX, argument):
python_path = self.os.path.join(test_dir,
self.os.path.basename(argument))
if self.os.path.isfile(python_path):
listed_python_tests.append(python_path)
else:
sys.stderr.write('Unable to find Python test %s' % argument)
errors_found = True
elif re.search(BINARY_TEST_REGEX, argument):
# This script also accepts binary test names prefixed with test/ for
# the convenience of typing them (can use path completions in the
# shell). Strips test/ prefix from the binary test names.
listed_binary_tests.append(self.os.path.basename(argument))
else:
sys.stderr.write('%s is neither test nor build directory' % argument)
errors_found = True
if errors_found:
return None
user_has_listed_tests = listed_python_tests or listed_binary_tests
if user_has_listed_tests:
selected_python_tests = listed_python_tests
else:
selected_python_tests = self._FindFilesByRegex(test_dir,
PYTHON_TEST_REGEX)
# TODO(vladl@google.com): skip unbuilt Python tests when -b is specified.
python_test_pairs = []
for directory in build_dirs:
for test in selected_python_tests:
config = _GetConfigFromBuildDir(directory)
file_name = os.path.basename(test)
if python_tests_to_skip and (config, file_name) in python_tests_to_skip:
print ('NOTE: %s is skipped for configuration %s, as it does not '
'work there.' % (file_name, config))
else:
python_test_pairs.append((directory, test))
binary_test_pairs = []
for directory in build_dirs:
if user_has_listed_tests:
binary_test_pairs.extend(
[(directory, self.os.path.join(directory, test))
for test in listed_binary_tests])
else:
tests = self._FindFilesByRegex(directory, BINARY_TEST_SEARCH_REGEX)
binary_test_pairs.extend([(directory, test) for test in tests])
return (python_test_pairs, binary_test_pairs)
def RunTests(self, python_tests, binary_tests):
"""Runs Python and binary tests and reports results to the standard output.
Args:
python_tests: List of Python tests to run in the form of tuples
(build directory, Python test script).
binary_tests: List of binary tests to run in the form of tuples
(build directory, binary file).
Returns:
The exit code the program should pass into sys.exit().
"""
if python_tests or binary_tests:
results = []
for directory, test in python_tests:
results.append((directory,
test,
self._RunPythonTest(test, directory) == 0))
for directory, test in binary_tests:
results.append((directory,
self.os.path.basename(test),
self._RunBinaryTest(test) == 0))
failed = [(directory, test)
for (directory, test, success) in results
if not success]
print
print '%d tests run.' % len(results)
if failed:
print 'The following %d tests failed:' % len(failed)
for (directory, test) in failed:
print '%s in %s' % (test, directory)
return 1
else:
print 'All tests passed!'
else: # No tests defined
print 'Nothing to test - no tests specified!'
return 0
def ParseArgs(project_name, argv=None, help_callback=None):
"""Parses the options run_tests.py uses."""
# Suppresses lint warning on unused arguments. These arguments are
# required by optparse, even though they are unused.
# pylint: disable-msg=W0613
def PrintHelp(option, opt, value, parser):
print HELP_MSG % {'proj': project_name}
sys.exit(1)
parser = optparse.OptionParser()
parser.add_option('-c',
action='store',
dest='configurations',
default=None)
parser.add_option('-a',
action='store_const',
dest='configurations',
default=None,
const='all')
parser.add_option('-b',
action='store_const',
dest='built_configurations',
default=False,
const=True)
# Replaces the built-in help with ours.
parser.remove_option('-h')
parser.add_option('-h', '--help',
action='callback',
callback=help_callback or PrintHelp)
return parser.parse_args(argv)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test for the gtest_xml_output module"""
__author__ = 'eefacm@gmail.com (Sean Mcafee)'
import errno
import os
import sys
from xml.dom import minidom, Node
import gtest_test_utils
import gtest_xml_test_utils
GTEST_OUTPUT_FLAG = "--gtest_output"
GTEST_DEFAULT_OUTPUT_FILE = "test_detail.xml"
GTEST_PROGRAM_NAME = "gtest_xml_output_unittest_"
SUPPORTS_STACK_TRACES = False
if SUPPORTS_STACK_TRACES:
STACK_TRACE_TEMPLATE = "\nStack trace:\n*"
else:
STACK_TRACE_TEMPLATE = ""
EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="15" failures="4" disabled="2" errors="0" time="*" name="AllTests">
<testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*">
<testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/>
</testsuite>
<testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*">
<testcase name="Fails" status="run" time="*" classname="FailedTest">
<failure message="Value of: 2
Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Value of: 2
Expected: 1%(stack)s]]></failure>
</testcase>
</testsuite>
<testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*">
<testcase name="Succeeds" status="run" time="*" classname="MixedResultTest"/>
<testcase name="Fails" status="run" time="*" classname="MixedResultTest">
<failure message="Value of: 2
Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Value of: 2
Expected: 1%(stack)s]]></failure>
<failure message="Value of: 3
Expected: 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Value of: 3
Expected: 2%(stack)s]]></failure>
</testcase>
<testcase name="DISABLED_test" status="notrun" time="*" classname="MixedResultTest"/>
</testsuite>
<testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" errors="0" time="*">
<testcase name="OutputsCData" status="run" time="*" classname="XmlQuotingTest">
<failure message="Failed
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]></top>" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Failed
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]><![CDATA[</top>%(stack)s]]></failure>
</testcase>
</testsuite>
<testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" errors="0" time="*">
<testcase name="InvalidCharactersInMessage" status="run" time="*" classname="InvalidCharactersTest">
<failure message="Failed
Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Failed
Invalid characters in brackets []%(stack)s]]></failure>
</testcase>
</testsuite>
<testsuite name="DisabledTest" tests="1" failures="0" disabled="1" errors="0" time="*">
<testcase name="DISABLED_test_not_run" status="notrun" time="*" classname="DisabledTest"/>
</testsuite>
<testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*">
<testcase name="OneProperty" status="run" time="*" classname="PropertyRecordingTest" key_1="1"/>
<testcase name="IntValuedProperty" status="run" time="*" classname="PropertyRecordingTest" key_int="1"/>
<testcase name="ThreeProperties" status="run" time="*" classname="PropertyRecordingTest" key_1="1" key_2="2" key_3="3"/>
<testcase name="TwoValuesForOneKeyUsesLastValue" status="run" time="*" classname="PropertyRecordingTest" key_1="2"/>
</testsuite>
<testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*">
<testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest" key="1"/>
<testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_int="1"/>
<testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_string="1"/>
</testsuite>
</testsuites>""" % {'stack': STACK_TRACE_TEMPLATE}
EXPECTED_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="0" failures="0" disabled="0" errors="0" time="*" name="AllTests">
</testsuites>"""
class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
"""
Unit test for Google Test's XML output functionality.
"""
def testNonEmptyXmlOutput(self):
"""
Runs a test program that generates a non-empty XML output, and
tests that the XML output is expected.
"""
self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY_XML, 1)
def testEmptyXmlOutput(self):
"""
Runs a test program that generates an empty XML output, and
tests that the XML output is expected.
"""
self._TestXmlOutput("gtest_no_test_unittest",
EXPECTED_EMPTY_XML, 0)
def testDefaultOutputFile(self):
"""
Confirms that Google Test produces an XML output file with the expected
default name if no name is explicitly specified.
"""
output_file = os.path.join(gtest_test_utils.GetTempDir(),
GTEST_DEFAULT_OUTPUT_FILE)
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(
"gtest_no_test_unittest")
try:
os.remove(output_file)
except OSError, e:
if e.errno != errno.ENOENT:
raise
p = gtest_test_utils.Subprocess(
[gtest_prog_path, "%s=xml" % GTEST_OUTPUT_FLAG],
working_dir=gtest_test_utils.GetTempDir())
self.assert_(p.exited)
self.assertEquals(0, p.exit_code)
self.assert_(os.path.isfile(output_file))
def testSuppressedXmlOutput(self):
"""
Tests that no XML file is generated if the default XML listener is
shut down before RUN_ALL_TESTS is invoked.
"""
xml_path = os.path.join(gtest_test_utils.GetTempDir(),
GTEST_PROGRAM_NAME + "out.xml")
if os.path.isfile(xml_path):
os.remove(xml_path)
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME)
command = [gtest_prog_path,
"%s=xml:%s" % (GTEST_OUTPUT_FLAG, xml_path),
"--shut_down_xml"]
p = gtest_test_utils.Subprocess(command)
if p.terminated_by_signal:
self.assert_(False,
"%s was killed by signal %d" % (gtest_prog_name, p.signal))
else:
self.assert_(p.exited)
self.assertEquals(1, p.exit_code,
"'%s' exited with code %s, which doesn't match "
"the expected exit code %s."
% (command, p.exit_code, 1))
self.assert_(not os.path.isfile(xml_path))
def _TestXmlOutput(self, gtest_prog_name, expected_xml, expected_exit_code):
"""
Asserts that the XML document generated by running the program
gtest_prog_name matches expected_xml, a string containing another
XML document. Furthermore, the program's exit code must be
expected_exit_code.
"""
xml_path = os.path.join(gtest_test_utils.GetTempDir(),
gtest_prog_name + "out.xml")
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name)
command = [gtest_prog_path, "%s=xml:%s" % (GTEST_OUTPUT_FLAG, xml_path)]
p = gtest_test_utils.Subprocess(command)
if p.terminated_by_signal:
self.assert_(False,
"%s was killed by signal %d" % (gtest_prog_name, p.signal))
else:
self.assert_(p.exited)
self.assertEquals(expected_exit_code, p.exit_code,
"'%s' exited with code %s, which doesn't match "
"the expected exit code %s."
% (command, p.exit_code, expected_exit_code))
expected = minidom.parseString(expected_xml)
actual = minidom.parse(xml_path)
self.NormalizeXml(actual.documentElement)
self.AssertEquivalentNodes(expected.documentElement,
actual.documentElement)
expected.unlink()
actual .unlink()
if __name__ == '__main__':
os.environ['GTEST_STACK_TRACE_DEPTH'] = '1'
gtest_test_utils.Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Verifies that Google Test correctly parses environment variables."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import gtest_test_utils
IS_WINDOWS = os.name == 'nt'
IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_env_var_test_')
environ = os.environ.copy()
def AssertEq(expected, actual):
if expected != actual:
print 'Expected: %s' % (expected,)
print ' Actual: %s' % (actual,)
raise AssertionError
def SetEnvVar(env_var, value):
"""Sets the env variable to 'value'; unsets it when 'value' is None."""
if value is not None:
environ[env_var] = value
elif env_var in environ:
del environ[env_var]
def GetFlag(flag):
"""Runs gtest_env_var_test_ and returns its output."""
args = [COMMAND]
if flag is not None:
args += [flag]
return gtest_test_utils.Subprocess(args, env=environ).output
def TestFlag(flag, test_val, default_val):
"""Verifies that the given flag is affected by the corresponding env var."""
env_var = 'GTEST_' + flag.upper()
SetEnvVar(env_var, test_val)
AssertEq(test_val, GetFlag(flag))
SetEnvVar(env_var, None)
AssertEq(default_val, GetFlag(flag))
class GTestEnvVarTest(gtest_test_utils.TestCase):
def testEnvVarAffectsFlag(self):
"""Tests that environment variable should affect the corresponding flag."""
TestFlag('break_on_failure', '1', '0')
TestFlag('color', 'yes', 'auto')
TestFlag('filter', 'FooTest.Bar', '*')
TestFlag('output', 'xml:tmp/foo.xml', '')
TestFlag('print_time', '0', '1')
TestFlag('repeat', '999', '1')
TestFlag('throw_on_failure', '1', '0')
TestFlag('death_test_style', 'threadsafe', 'fast')
if IS_WINDOWS:
TestFlag('catch_exceptions', '1', '0')
if IS_LINUX:
TestFlag('death_test_use_fork', '1', '0')
TestFlag('stack_trace_depth', '0', '100')
if __name__ == '__main__':
gtest_test_utils.Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test utilities for gtest_xml_output"""
__author__ = 'eefacm@gmail.com (Sean Mcafee)'
import re
from xml.dom import minidom, Node
import gtest_test_utils
GTEST_OUTPUT_FLAG = "--gtest_output"
GTEST_DEFAULT_OUTPUT_FILE = "test_detail.xml"
class GTestXMLTestCase(gtest_test_utils.TestCase):
"""
Base class for tests of Google Test's XML output functionality.
"""
def AssertEquivalentNodes(self, expected_node, actual_node):
"""
Asserts that actual_node (a DOM node object) is equivalent to
expected_node (another DOM node object), in that either both of
them are CDATA nodes and have the same value, or both are DOM
elements and actual_node meets all of the following conditions:
* It has the same tag name as expected_node.
* It has the same set of attributes as expected_node, each with
the same value as the corresponding attribute of expected_node.
An exception is any attribute named "time", which needs only be
convertible to a floating-point number.
* It has an equivalent set of child nodes (including elements and
CDATA sections) as expected_node. Note that we ignore the
order of the children as they are not guaranteed to be in any
particular order.
"""
if expected_node.nodeType == Node.CDATA_SECTION_NODE:
self.assertEquals(Node.CDATA_SECTION_NODE, actual_node.nodeType)
self.assertEquals(expected_node.nodeValue, actual_node.nodeValue)
return
self.assertEquals(Node.ELEMENT_NODE, actual_node.nodeType)
self.assertEquals(Node.ELEMENT_NODE, expected_node.nodeType)
self.assertEquals(expected_node.tagName, actual_node.tagName)
expected_attributes = expected_node.attributes
actual_attributes = actual_node .attributes
self.assertEquals(
expected_attributes.length, actual_attributes.length,
"attribute numbers differ in element " + actual_node.tagName)
for i in range(expected_attributes.length):
expected_attr = expected_attributes.item(i)
actual_attr = actual_attributes.get(expected_attr.name)
self.assert_(
actual_attr is not None,
"expected attribute %s not found in element %s" %
(expected_attr.name, actual_node.tagName))
self.assertEquals(expected_attr.value, actual_attr.value,
" values of attribute %s in element %s differ" %
(expected_attr.name, actual_node.tagName))
expected_children = self._GetChildren(expected_node)
actual_children = self._GetChildren(actual_node)
self.assertEquals(
len(expected_children), len(actual_children),
"number of child elements differ in element " + actual_node.tagName)
for child_id, child in expected_children.iteritems():
self.assert_(child_id in actual_children,
'<%s> is not in <%s> (in element %s)' %
(child_id, actual_children, actual_node.tagName))
self.AssertEquivalentNodes(child, actual_children[child_id])
identifying_attribute = {
"testsuites": "name",
"testsuite": "name",
"testcase": "name",
"failure": "message",
}
def _GetChildren(self, element):
"""
Fetches all of the child nodes of element, a DOM Element object.
Returns them as the values of a dictionary keyed by the IDs of the
children. For <testsuites>, <testsuite> and <testcase> elements, the ID
is the value of their "name" attribute; for <failure> elements, it is
the value of the "message" attribute; CDATA sections and non-whitespace
text nodes are concatenated into a single CDATA section with ID
"detail". An exception is raised if any element other than the above
four is encountered, if two child elements with the same identifying
attributes are encountered, or if any other type of node is encountered.
"""
children = {}
for child in element.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
self.assert_(child.tagName in self.identifying_attribute,
"Encountered unknown element <%s>" % child.tagName)
childID = child.getAttribute(self.identifying_attribute[child.tagName])
self.assert_(childID not in children)
children[childID] = child
elif child.nodeType in [Node.TEXT_NODE, Node.CDATA_SECTION_NODE]:
if "detail" not in children:
if (child.nodeType == Node.CDATA_SECTION_NODE or
not child.nodeValue.isspace()):
children["detail"] = child.ownerDocument.createCDATASection(
child.nodeValue)
else:
children["detail"].nodeValue += child.nodeValue
else:
self.fail("Encountered unexpected node type %d" % child.nodeType)
return children
def NormalizeXml(self, element):
"""
Normalizes Google Test's XML output to eliminate references to transient
information that may change from run to run.
* The "time" attribute of <testsuites>, <testsuite> and <testcase>
elements is replaced with a single asterisk, if it contains
only digit characters.
* The line number reported in the first line of the "message"
attribute of <failure> elements is replaced with a single asterisk.
* The directory names in file paths are removed.
* The stack traces are removed.
"""
if element.tagName in ("testsuites", "testsuite", "testcase"):
time = element.getAttributeNode("time")
time.value = re.sub(r"^\d+(\.\d+)?$", "*", time.value)
elif element.tagName == "failure":
for child in element.childNodes:
if child.nodeType == Node.CDATA_SECTION_NODE:
# Removes the source line number.
cdata = re.sub(r"^.*[/\\](.*:)\d+\n", "\\1*\n", child.nodeValue)
# Removes the actual stack trace.
child.nodeValue = re.sub(r"\nStack trace:\n(.|\n)*",
"", cdata)
for child in element.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
self.NormalizeXml(child)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test utilities for Google C++ Testing Framework."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import atexit
import os
import shutil
import sys
import tempfile
import unittest
_test_module = unittest
# Suppresses the 'Import not at the top of the file' lint complaint.
# pylint: disable-msg=C6204
try:
import subprocess
_SUBPROCESS_MODULE_AVAILABLE = True
except:
import popen2
_SUBPROCESS_MODULE_AVAILABLE = False
# pylint: enable-msg=C6204
GTEST_OUTPUT_VAR_NAME = 'GTEST_OUTPUT'
IS_WINDOWS = os.name == 'nt'
IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0]
# Here we expose a class from a particular module, depending on the
# environment. The comment suppresses the 'Invalid variable name' lint
# complaint.
TestCase = _test_module.TestCase # pylint: disable-msg=C6409
# Initially maps a flag to its default value. After
# _ParseAndStripGTestFlags() is called, maps a flag to its actual value.
_flag_map = {'source_dir': os.path.dirname(sys.argv[0]),
'build_dir': os.path.dirname(sys.argv[0])}
_gtest_flags_are_parsed = False
def _ParseAndStripGTestFlags(argv):
"""Parses and strips Google Test flags from argv. This is idempotent."""
# Suppresses the lint complaint about a global variable since we need it
# here to maintain module-wide state.
global _gtest_flags_are_parsed # pylint: disable-msg=W0603
if _gtest_flags_are_parsed:
return
_gtest_flags_are_parsed = True
for flag in _flag_map:
# The environment variable overrides the default value.
if flag.upper() in os.environ:
_flag_map[flag] = os.environ[flag.upper()]
# The command line flag overrides the environment variable.
i = 1 # Skips the program name.
while i < len(argv):
prefix = '--' + flag + '='
if argv[i].startswith(prefix):
_flag_map[flag] = argv[i][len(prefix):]
del argv[i]
break
else:
# We don't increment i in case we just found a --gtest_* flag
# and removed it from argv.
i += 1
def GetFlag(flag):
"""Returns the value of the given flag."""
# In case GetFlag() is called before Main(), we always call
# _ParseAndStripGTestFlags() here to make sure the --gtest_* flags
# are parsed.
_ParseAndStripGTestFlags(sys.argv)
return _flag_map[flag]
def GetSourceDir():
"""Returns the absolute path of the directory where the .py files are."""
return os.path.abspath(GetFlag('source_dir'))
def GetBuildDir():
"""Returns the absolute path of the directory where the test binaries are."""
return os.path.abspath(GetFlag('build_dir'))
_temp_dir = None
def _RemoveTempDir():
if _temp_dir:
shutil.rmtree(_temp_dir, ignore_errors=True)
atexit.register(_RemoveTempDir)
def GetTempDir():
"""Returns a directory for temporary files."""
global _temp_dir
if not _temp_dir:
_temp_dir = tempfile.mkdtemp()
return _temp_dir
def GetTestExecutablePath(executable_name, build_dir=None):
"""Returns the absolute path of the test binary given its name.
The function will print a message and abort the program if the resulting file
doesn't exist.
Args:
executable_name: name of the test binary that the test script runs.
build_dir: directory where to look for executables, by default
the result of GetBuildDir().
Returns:
The absolute path of the test binary.
"""
path = os.path.abspath(os.path.join(build_dir or GetBuildDir(),
executable_name))
if (IS_WINDOWS or IS_CYGWIN) and not path.endswith('.exe'):
path += '.exe'
if not os.path.exists(path):
message = (
'Unable to find the test binary. Please make sure to provide path\n'
'to the binary via the --build_dir flag or the BUILD_DIR\n'
'environment variable. For convenient use, invoke this script via\n'
'mk_test.py.\n'
# TODO(vladl@google.com): change mk_test.py to test.py after renaming
# the file.
'Please run mk_test.py -h for help.')
print >> sys.stderr, message
sys.exit(1)
return path
def GetExitStatus(exit_code):
"""Returns the argument to exit(), or -1 if exit() wasn't called.
Args:
exit_code: the result value of os.system(command).
"""
if os.name == 'nt':
# On Windows, os.WEXITSTATUS() doesn't work and os.system() returns
# the argument to exit() directly.
return exit_code
else:
# On Unix, os.WEXITSTATUS() must be used to extract the exit status
# from the result of os.system().
if os.WIFEXITED(exit_code):
return os.WEXITSTATUS(exit_code)
else:
return -1
class Subprocess:
def __init__(self, command, working_dir=None, capture_stderr=True, env=None):
"""Changes into a specified directory, if provided, and executes a command.
Restores the old directory afterwards.
Args:
command: The command to run, in the form of sys.argv.
working_dir: The directory to change into.
capture_stderr: Determines whether to capture stderr in the output member
or to discard it.
env: Dictionary with environment to pass to the subprocess.
Returns:
An object that represents outcome of the executed process. It has the
following attributes:
terminated_by_signal True iff the child process has been terminated
by a signal.
signal Sygnal that terminated the child process.
exited True iff the child process exited normally.
exit_code The code with which the child process exited.
output Child process's stdout and stderr output
combined in a string.
"""
# The subprocess module is the preferrable way of running programs
# since it is available and behaves consistently on all platforms,
# including Windows. But it is only available starting in python 2.4.
# In earlier python versions, we revert to the popen2 module, which is
# available in python 2.0 and later but doesn't provide required
# functionality (Popen4) under Windows. This allows us to support Mac
# OS X 10.4 Tiger, which has python 2.3 installed.
if _SUBPROCESS_MODULE_AVAILABLE:
if capture_stderr:
stderr = subprocess.STDOUT
else:
stderr = subprocess.PIPE
p = subprocess.Popen(command,
stdout=subprocess.PIPE, stderr=stderr,
cwd=working_dir, universal_newlines=True, env=env)
# communicate returns a tuple with the file obect for the child's
# output.
self.output = p.communicate()[0]
self._return_code = p.returncode
else:
old_dir = os.getcwd()
def _ReplaceEnvDict(dest, src):
# Changes made by os.environ.clear are not inheritable by child
# processes until Python 2.6. To produce inheritable changes we have
# to delete environment items with the del statement.
for key in dest:
del dest[key]
dest.update(src)
# When 'env' is not None, backup the environment variables and replace
# them with the passed 'env'. When 'env' is None, we simply use the
# current 'os.environ' for compatibility with the subprocess.Popen
# semantics used above.
if env is not None:
old_environ = os.environ.copy()
_ReplaceEnvDict(os.environ, env)
try:
if working_dir is not None:
os.chdir(working_dir)
if capture_stderr:
p = popen2.Popen4(command)
else:
p = popen2.Popen3(command)
p.tochild.close()
self.output = p.fromchild.read()
ret_code = p.wait()
finally:
os.chdir(old_dir)
# Restore the old environment variables
# if they were replaced.
if env is not None:
_ReplaceEnvDict(os.environ, old_environ)
# Converts ret_code to match the semantics of
# subprocess.Popen.returncode.
if os.WIFSIGNALED(ret_code):
self._return_code = -os.WTERMSIG(ret_code)
else: # os.WIFEXITED(ret_code) should return True here.
self._return_code = os.WEXITSTATUS(ret_code)
if self._return_code < 0:
self.terminated_by_signal = True
self.exited = False
self.signal = -self._return_code
else:
self.terminated_by_signal = False
self.exited = True
self.exit_code = self._return_code
def Main():
"""Runs the unit test."""
# We must call _ParseAndStripGTestFlags() before calling
# unittest.main(). Otherwise the latter will be confused by the
# --gtest_* flags.
_ParseAndStripGTestFlags(sys.argv)
# The tested binaries should not be writing XML output files unless the
# script explicitly instructs them to.
# TODO(vladl@google.com): Move this into Subprocess when we implement
# passing environment into it as a parameter.
if GTEST_OUTPUT_VAR_NAME in os.environ:
del os.environ[GTEST_OUTPUT_VAR_NAME]
_test_module.main()
| Python |
#!/usr/bin/env python
#
# Copyright 2008, Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Runs the specified tests for Google Test.
This script requires Python 2.3 or higher. To learn the usage, run it
with -h.
"""
import os
import sys
SCRIPT_DIR = os.path.dirname(__file__) or '.'
sys.path.append(os.path.join(SCRIPT_DIR, 'test'))
import run_tests_util
def _Main():
"""Runs all tests for Google Test."""
options, args = run_tests_util.ParseArgs('gtest')
test_runner = run_tests_util.TestRunner(script_dir=SCRIPT_DIR)
tests = test_runner.GetTestsToRun(args,
options.configurations,
options.built_configurations)
if not tests:
sys.exit(1) # Incorrect parameters given, abort execution.
sys.exit(test_runner.RunTests(tests[0], tests[1]))
if __name__ == '__main__':
_Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tool for uploading diffs from a version control system to the codereview app.
Usage summary: upload.py [options] [-- diff_options]
Diff options are passed to the diff command of the underlying system.
Supported version control systems:
Git
Mercurial
Subversion
It is important for Git/Mercurial users to specify a tree/node/branch to diff
against by using the '--rev' option.
"""
# This code is derived from appcfg.py in the App Engine SDK (open source),
# and from ASPN recipe #146306.
import cookielib
import getpass
import logging
import md5
import mimetypes
import optparse
import os
import re
import socket
import subprocess
import sys
import urllib
import urllib2
import urlparse
try:
import readline
except ImportError:
pass
# The logging verbosity:
# 0: Errors only.
# 1: Status messages.
# 2: Info logs.
# 3: Debug logs.
verbosity = 1
# Max size of patch or base file.
MAX_UPLOAD_SIZE = 900 * 1024
def GetEmail(prompt):
"""Prompts the user for their email address and returns it.
The last used email address is saved to a file and offered up as a suggestion
to the user. If the user presses enter without typing in anything the last
used email address is used. If the user enters a new address, it is saved
for next time we prompt.
"""
last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
last_email = ""
if os.path.exists(last_email_file_name):
try:
last_email_file = open(last_email_file_name, "r")
last_email = last_email_file.readline().strip("\n")
last_email_file.close()
prompt += " [%s]" % last_email
except IOError, e:
pass
email = raw_input(prompt + ": ").strip()
if email:
try:
last_email_file = open(last_email_file_name, "w")
last_email_file.write(email)
last_email_file.close()
except IOError, e:
pass
else:
email = last_email
return email
def StatusUpdate(msg):
"""Print a status message to stdout.
If 'verbosity' is greater than 0, print the message.
Args:
msg: The string to print.
"""
if verbosity > 0:
print msg
def ErrorExit(msg):
"""Print an error message to stderr and exit."""
print >>sys.stderr, msg
sys.exit(1)
class ClientLoginError(urllib2.HTTPError):
"""Raised to indicate there was an error authenticating with ClientLogin."""
def __init__(self, url, code, msg, headers, args):
urllib2.HTTPError.__init__(self, url, code, msg, headers, None)
self.args = args
self.reason = args["Error"]
class AbstractRpcServer(object):
"""Provides a common interface for a simple RPC server."""
def __init__(self, host, auth_function, host_override=None, extra_headers={},
save_cookies=False):
"""Creates a new HttpRpcServer.
Args:
host: The host to send requests to.
auth_function: A function that takes no arguments and returns an
(email, password) tuple when called. Will be called if authentication
is required.
host_override: The host header to send to the server (defaults to host).
extra_headers: A dict of extra headers to append to every request.
save_cookies: If True, save the authentication cookies to local disk.
If False, use an in-memory cookiejar instead. Subclasses must
implement this functionality. Defaults to False.
"""
self.host = host
self.host_override = host_override
self.auth_function = auth_function
self.authenticated = False
self.extra_headers = extra_headers
self.save_cookies = save_cookies
self.opener = self._GetOpener()
if self.host_override:
logging.info("Server: %s; Host: %s", self.host, self.host_override)
else:
logging.info("Server: %s", self.host)
def _GetOpener(self):
"""Returns an OpenerDirector for making HTTP requests.
Returns:
A urllib2.OpenerDirector object.
"""
raise NotImplementedError()
def _CreateRequest(self, url, data=None):
"""Creates a new urllib request."""
logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
req = urllib2.Request(url, data=data)
if self.host_override:
req.add_header("Host", self.host_override)
for key, value in self.extra_headers.iteritems():
req.add_header(key, value)
return req
def _GetAuthToken(self, email, password):
"""Uses ClientLogin to authenticate the user, returning an auth token.
Args:
email: The user's email address
password: The user's password
Raises:
ClientLoginError: If there was an error authenticating with ClientLogin.
HTTPError: If there was some other form of HTTP error.
Returns:
The authentication token returned by ClientLogin.
"""
account_type = "GOOGLE"
if self.host.endswith(".google.com"):
# Needed for use inside Google.
account_type = "HOSTED"
req = self._CreateRequest(
url="https://www.google.com/accounts/ClientLogin",
data=urllib.urlencode({
"Email": email,
"Passwd": password,
"service": "ah",
"source": "rietveld-codereview-upload",
"accountType": account_type,
}),
)
try:
response = self.opener.open(req)
response_body = response.read()
response_dict = dict(x.split("=")
for x in response_body.split("\n") if x)
return response_dict["Auth"]
except urllib2.HTTPError, e:
if e.code == 403:
body = e.read()
response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
raise ClientLoginError(req.get_full_url(), e.code, e.msg,
e.headers, response_dict)
else:
raise
def _GetAuthCookie(self, auth_token):
"""Fetches authentication cookies for an authentication token.
Args:
auth_token: The authentication token returned by ClientLogin.
Raises:
HTTPError: If there was an error fetching the authentication cookies.
"""
# This is a dummy value to allow us to identify when we're successful.
continue_location = "http://localhost/"
args = {"continue": continue_location, "auth": auth_token}
req = self._CreateRequest("http://%s/_ah/login?%s" %
(self.host, urllib.urlencode(args)))
try:
response = self.opener.open(req)
except urllib2.HTTPError, e:
response = e
if (response.code != 302 or
response.info()["location"] != continue_location):
raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg,
response.headers, response.fp)
self.authenticated = True
def _Authenticate(self):
"""Authenticates the user.
The authentication process works as follows:
1) We get a username and password from the user
2) We use ClientLogin to obtain an AUTH token for the user
(see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
3) We pass the auth token to /_ah/login on the server to obtain an
authentication cookie. If login was successful, it tries to redirect
us to the URL we provided.
If we attempt to access the upload API without first obtaining an
authentication cookie, it returns a 401 response and directs us to
authenticate ourselves with ClientLogin.
"""
for i in range(3):
credentials = self.auth_function()
try:
auth_token = self._GetAuthToken(credentials[0], credentials[1])
except ClientLoginError, e:
if e.reason == "BadAuthentication":
print >>sys.stderr, "Invalid username or password."
continue
if e.reason == "CaptchaRequired":
print >>sys.stderr, (
"Please go to\n"
"https://www.google.com/accounts/DisplayUnlockCaptcha\n"
"and verify you are a human. Then try again.")
break
if e.reason == "NotVerified":
print >>sys.stderr, "Account not verified."
break
if e.reason == "TermsNotAgreed":
print >>sys.stderr, "User has not agreed to TOS."
break
if e.reason == "AccountDeleted":
print >>sys.stderr, "The user account has been deleted."
break
if e.reason == "AccountDisabled":
print >>sys.stderr, "The user account has been disabled."
break
if e.reason == "ServiceDisabled":
print >>sys.stderr, ("The user's access to the service has been "
"disabled.")
break
if e.reason == "ServiceUnavailable":
print >>sys.stderr, "The service is not available; try again later."
break
raise
self._GetAuthCookie(auth_token)
return
def Send(self, request_path, payload=None,
content_type="application/octet-stream",
timeout=None,
**kwargs):
"""Sends an RPC and returns the response.
Args:
request_path: The path to send the request to, eg /api/appversion/create.
payload: The body of the request, or None to send an empty request.
content_type: The Content-Type header to use.
timeout: timeout in seconds; default None i.e. no timeout.
(Note: for large requests on OS X, the timeout doesn't work right.)
kwargs: Any keyword arguments are converted into query string parameters.
Returns:
The response body, as a string.
"""
# TODO: Don't require authentication. Let the server say
# whether it is necessary.
if not self.authenticated:
self._Authenticate()
old_timeout = socket.getdefaulttimeout()
socket.setdefaulttimeout(timeout)
try:
tries = 0
while True:
tries += 1
args = dict(kwargs)
url = "http://%s%s" % (self.host, request_path)
if args:
url += "?" + urllib.urlencode(args)
req = self._CreateRequest(url=url, data=payload)
req.add_header("Content-Type", content_type)
try:
f = self.opener.open(req)
response = f.read()
f.close()
return response
except urllib2.HTTPError, e:
if tries > 3:
raise
elif e.code == 401:
self._Authenticate()
## elif e.code >= 500 and e.code < 600:
## # Server Error - try again.
## continue
else:
raise
finally:
socket.setdefaulttimeout(old_timeout)
class HttpRpcServer(AbstractRpcServer):
"""Provides a simplified RPC-style interface for HTTP requests."""
def _Authenticate(self):
"""Save the cookie jar after authentication."""
super(HttpRpcServer, self)._Authenticate()
if self.save_cookies:
StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
self.cookie_jar.save()
def _GetOpener(self):
"""Returns an OpenerDirector that supports cookies and ignores redirects.
Returns:
A urllib2.OpenerDirector object.
"""
opener = urllib2.OpenerDirector()
opener.add_handler(urllib2.ProxyHandler())
opener.add_handler(urllib2.UnknownHandler())
opener.add_handler(urllib2.HTTPHandler())
opener.add_handler(urllib2.HTTPDefaultErrorHandler())
opener.add_handler(urllib2.HTTPSHandler())
opener.add_handler(urllib2.HTTPErrorProcessor())
if self.save_cookies:
self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies")
self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
if os.path.exists(self.cookie_file):
try:
self.cookie_jar.load()
self.authenticated = True
StatusUpdate("Loaded authentication cookies from %s" %
self.cookie_file)
except (cookielib.LoadError, IOError):
# Failed to load cookies - just ignore them.
pass
else:
# Create an empty cookie file with mode 600
fd = os.open(self.cookie_file, os.O_CREAT, 0600)
os.close(fd)
# Always chmod the cookie file
os.chmod(self.cookie_file, 0600)
else:
# Don't save cookies across runs of update.py.
self.cookie_jar = cookielib.CookieJar()
opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar))
return opener
parser = optparse.OptionParser(usage="%prog [options] [-- diff_options]")
parser.add_option("-y", "--assume_yes", action="store_true",
dest="assume_yes", default=False,
help="Assume that the answer to yes/no questions is 'yes'.")
# Logging
group = parser.add_option_group("Logging options")
group.add_option("-q", "--quiet", action="store_const", const=0,
dest="verbose", help="Print errors only.")
group.add_option("-v", "--verbose", action="store_const", const=2,
dest="verbose", default=1,
help="Print info level logs (default).")
group.add_option("--noisy", action="store_const", const=3,
dest="verbose", help="Print all logs.")
# Review server
group = parser.add_option_group("Review server options")
group.add_option("-s", "--server", action="store", dest="server",
default="codereview.appspot.com",
metavar="SERVER",
help=("The server to upload to. The format is host[:port]. "
"Defaults to 'codereview.appspot.com'."))
group.add_option("-e", "--email", action="store", dest="email",
metavar="EMAIL", default=None,
help="The username to use. Will prompt if omitted.")
group.add_option("-H", "--host", action="store", dest="host",
metavar="HOST", default=None,
help="Overrides the Host header sent with all RPCs.")
group.add_option("--no_cookies", action="store_false",
dest="save_cookies", default=True,
help="Do not save authentication cookies to local disk.")
# Issue
group = parser.add_option_group("Issue options")
group.add_option("-d", "--description", action="store", dest="description",
metavar="DESCRIPTION", default=None,
help="Optional description when creating an issue.")
group.add_option("-f", "--description_file", action="store",
dest="description_file", metavar="DESCRIPTION_FILE",
default=None,
help="Optional path of a file that contains "
"the description when creating an issue.")
group.add_option("-r", "--reviewers", action="store", dest="reviewers",
metavar="REVIEWERS", default=None,
help="Add reviewers (comma separated email addresses).")
group.add_option("--cc", action="store", dest="cc",
metavar="CC", default=None,
help="Add CC (comma separated email addresses).")
# Upload options
group = parser.add_option_group("Patch options")
group.add_option("-m", "--message", action="store", dest="message",
metavar="MESSAGE", default=None,
help="A message to identify the patch. "
"Will prompt if omitted.")
group.add_option("-i", "--issue", type="int", action="store",
metavar="ISSUE", default=None,
help="Issue number to which to add. Defaults to new issue.")
group.add_option("--download_base", action="store_true",
dest="download_base", default=False,
help="Base files will be downloaded by the server "
"(side-by-side diffs may not work on files with CRs).")
group.add_option("--rev", action="store", dest="revision",
metavar="REV", default=None,
help="Branch/tree/revision to diff against (used by DVCS).")
group.add_option("--send_mail", action="store_true",
dest="send_mail", default=False,
help="Send notification email to reviewers.")
def GetRpcServer(options):
"""Returns an instance of an AbstractRpcServer.
Returns:
A new AbstractRpcServer, on which RPC calls can be made.
"""
rpc_server_class = HttpRpcServer
def GetUserCredentials():
"""Prompts the user for a username and password."""
email = options.email
if email is None:
email = GetEmail("Email (login for uploading to %s)" % options.server)
password = getpass.getpass("Password for %s: " % email)
return (email, password)
# If this is the dev_appserver, use fake authentication.
host = (options.host or options.server).lower()
if host == "localhost" or host.startswith("localhost:"):
email = options.email
if email is None:
email = "test@example.com"
logging.info("Using debug user %s. Override with --email" % email)
server = rpc_server_class(
options.server,
lambda: (email, "password"),
host_override=options.host,
extra_headers={"Cookie":
'dev_appserver_login="%s:False"' % email},
save_cookies=options.save_cookies)
# Don't try to talk to ClientLogin.
server.authenticated = True
return server
return rpc_server_class(options.server, GetUserCredentials,
host_override=options.host,
save_cookies=options.save_cookies)
def EncodeMultipartFormData(fields, files):
"""Encode form fields for multipart/form-data.
Args:
fields: A sequence of (name, value) elements for regular form fields.
files: A sequence of (name, filename, value) elements for data to be
uploaded as files.
Returns:
(content_type, body) ready for httplib.HTTP instance.
Source:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
"""
BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-'
CRLF = '\r\n'
lines = []
for (key, value) in fields:
lines.append('--' + BOUNDARY)
lines.append('Content-Disposition: form-data; name="%s"' % key)
lines.append('')
lines.append(value)
for (key, filename, value) in files:
lines.append('--' + BOUNDARY)
lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' %
(key, filename))
lines.append('Content-Type: %s' % GetContentType(filename))
lines.append('')
lines.append(value)
lines.append('--' + BOUNDARY + '--')
lines.append('')
body = CRLF.join(lines)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
def GetContentType(filename):
"""Helper to guess the content-type from the filename."""
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
# Use a shell for subcommands on Windows to get a PATH search.
use_shell = sys.platform.startswith("win")
def RunShellWithReturnCode(command, print_output=False,
universal_newlines=True):
"""Executes a command and returns the output from stdout and the return code.
Args:
command: Command to execute.
print_output: If True, the output is printed to stdout.
If False, both stdout and stderr are ignored.
universal_newlines: Use universal_newlines flag (default: True).
Returns:
Tuple (output, return code)
"""
logging.info("Running %s", command)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=use_shell, universal_newlines=universal_newlines)
if print_output:
output_array = []
while True:
line = p.stdout.readline()
if not line:
break
print line.strip("\n")
output_array.append(line)
output = "".join(output_array)
else:
output = p.stdout.read()
p.wait()
errout = p.stderr.read()
if print_output and errout:
print >>sys.stderr, errout
p.stdout.close()
p.stderr.close()
return output, p.returncode
def RunShell(command, silent_ok=False, universal_newlines=True,
print_output=False):
data, retcode = RunShellWithReturnCode(command, print_output,
universal_newlines)
if retcode:
ErrorExit("Got error status from %s:\n%s" % (command, data))
if not silent_ok and not data:
ErrorExit("No output from %s" % command)
return data
class VersionControlSystem(object):
"""Abstract base class providing an interface to the VCS."""
def __init__(self, options):
"""Constructor.
Args:
options: Command line options.
"""
self.options = options
def GenerateDiff(self, args):
"""Return the current diff as a string.
Args:
args: Extra arguments to pass to the diff command.
"""
raise NotImplementedError(
"abstract method -- subclass %s must override" % self.__class__)
def GetUnknownFiles(self):
"""Return a list of files unknown to the VCS."""
raise NotImplementedError(
"abstract method -- subclass %s must override" % self.__class__)
def CheckForUnknownFiles(self):
"""Show an "are you sure?" prompt if there are unknown files."""
unknown_files = self.GetUnknownFiles()
if unknown_files:
print "The following files are not added to version control:"
for line in unknown_files:
print line
prompt = "Are you sure to continue?(y/N) "
answer = raw_input(prompt).strip()
if answer != "y":
ErrorExit("User aborted")
def GetBaseFile(self, filename):
"""Get the content of the upstream version of a file.
Returns:
A tuple (base_content, new_content, is_binary, status)
base_content: The contents of the base file.
new_content: For text files, this is empty. For binary files, this is
the contents of the new file, since the diff output won't contain
information to reconstruct the current file.
is_binary: True iff the file is binary.
status: The status of the file.
"""
raise NotImplementedError(
"abstract method -- subclass %s must override" % self.__class__)
def GetBaseFiles(self, diff):
"""Helper that calls GetBase file for each file in the patch.
Returns:
A dictionary that maps from filename to GetBaseFile's tuple. Filenames
are retrieved based on lines that start with "Index:" or
"Property changes on:".
"""
files = {}
for line in diff.splitlines(True):
if line.startswith('Index:') or line.startswith('Property changes on:'):
unused, filename = line.split(':', 1)
# On Windows if a file has property changes its filename uses '\'
# instead of '/'.
filename = filename.strip().replace('\\', '/')
files[filename] = self.GetBaseFile(filename)
return files
def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options,
files):
"""Uploads the base files (and if necessary, the current ones as well)."""
def UploadFile(filename, file_id, content, is_binary, status, is_base):
"""Uploads a file to the server."""
file_too_large = False
if is_base:
type = "base"
else:
type = "current"
if len(content) > MAX_UPLOAD_SIZE:
print ("Not uploading the %s file for %s because it's too large." %
(type, filename))
file_too_large = True
content = ""
checksum = md5.new(content).hexdigest()
if options.verbose > 0 and not file_too_large:
print "Uploading %s file for %s" % (type, filename)
url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id)
form_fields = [("filename", filename),
("status", status),
("checksum", checksum),
("is_binary", str(is_binary)),
("is_current", str(not is_base)),
]
if file_too_large:
form_fields.append(("file_too_large", "1"))
if options.email:
form_fields.append(("user", options.email))
ctype, body = EncodeMultipartFormData(form_fields,
[("data", filename, content)])
response_body = rpc_server.Send(url, body,
content_type=ctype)
if not response_body.startswith("OK"):
StatusUpdate(" --> %s" % response_body)
sys.exit(1)
patches = dict()
[patches.setdefault(v, k) for k, v in patch_list]
for filename in patches.keys():
base_content, new_content, is_binary, status = files[filename]
file_id_str = patches.get(filename)
if file_id_str.find("nobase") != -1:
base_content = None
file_id_str = file_id_str[file_id_str.rfind("_") + 1:]
file_id = int(file_id_str)
if base_content != None:
UploadFile(filename, file_id, base_content, is_binary, status, True)
if new_content != None:
UploadFile(filename, file_id, new_content, is_binary, status, False)
def IsImage(self, filename):
"""Returns true if the filename has an image extension."""
mimetype = mimetypes.guess_type(filename)[0]
if not mimetype:
return False
return mimetype.startswith("image/")
class SubversionVCS(VersionControlSystem):
"""Implementation of the VersionControlSystem interface for Subversion."""
def __init__(self, options):
super(SubversionVCS, self).__init__(options)
if self.options.revision:
match = re.match(r"(\d+)(:(\d+))?", self.options.revision)
if not match:
ErrorExit("Invalid Subversion revision %s." % self.options.revision)
self.rev_start = match.group(1)
self.rev_end = match.group(3)
else:
self.rev_start = self.rev_end = None
# Cache output from "svn list -r REVNO dirname".
# Keys: dirname, Values: 2-tuple (ouput for start rev and end rev).
self.svnls_cache = {}
# SVN base URL is required to fetch files deleted in an older revision.
# Result is cached to not guess it over and over again in GetBaseFile().
required = self.options.download_base or self.options.revision is not None
self.svn_base = self._GuessBase(required)
def GuessBase(self, required):
"""Wrapper for _GuessBase."""
return self.svn_base
def _GuessBase(self, required):
"""Returns the SVN base URL.
Args:
required: If true, exits if the url can't be guessed, otherwise None is
returned.
"""
info = RunShell(["svn", "info"])
for line in info.splitlines():
words = line.split()
if len(words) == 2 and words[0] == "URL:":
url = words[1]
scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
username, netloc = urllib.splituser(netloc)
if username:
logging.info("Removed username from base URL")
if netloc.endswith("svn.python.org"):
if netloc == "svn.python.org":
if path.startswith("/projects/"):
path = path[9:]
elif netloc != "pythondev@svn.python.org":
ErrorExit("Unrecognized Python URL: %s" % url)
base = "http://svn.python.org/view/*checkout*%s/" % path
logging.info("Guessed Python base = %s", base)
elif netloc.endswith("svn.collab.net"):
if path.startswith("/repos/"):
path = path[6:]
base = "http://svn.collab.net/viewvc/*checkout*%s/" % path
logging.info("Guessed CollabNet base = %s", base)
elif netloc.endswith(".googlecode.com"):
path = path + "/"
base = urlparse.urlunparse(("http", netloc, path, params,
query, fragment))
logging.info("Guessed Google Code base = %s", base)
else:
path = path + "/"
base = urlparse.urlunparse((scheme, netloc, path, params,
query, fragment))
logging.info("Guessed base = %s", base)
return base
if required:
ErrorExit("Can't find URL in output from svn info")
return None
def GenerateDiff(self, args):
cmd = ["svn", "diff"]
if self.options.revision:
cmd += ["-r", self.options.revision]
cmd.extend(args)
data = RunShell(cmd)
count = 0
for line in data.splitlines():
if line.startswith("Index:") or line.startswith("Property changes on:"):
count += 1
logging.info(line)
if not count:
ErrorExit("No valid patches found in output from svn diff")
return data
def _CollapseKeywords(self, content, keyword_str):
"""Collapses SVN keywords."""
# svn cat translates keywords but svn diff doesn't. As a result of this
# behavior patching.PatchChunks() fails with a chunk mismatch error.
# This part was originally written by the Review Board development team
# who had the same problem (http://reviews.review-board.org/r/276/).
# Mapping of keywords to known aliases
svn_keywords = {
# Standard keywords
'Date': ['Date', 'LastChangedDate'],
'Revision': ['Revision', 'LastChangedRevision', 'Rev'],
'Author': ['Author', 'LastChangedBy'],
'HeadURL': ['HeadURL', 'URL'],
'Id': ['Id'],
# Aliases
'LastChangedDate': ['LastChangedDate', 'Date'],
'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'],
'LastChangedBy': ['LastChangedBy', 'Author'],
'URL': ['URL', 'HeadURL'],
}
def repl(m):
if m.group(2):
return "$%s::%s$" % (m.group(1), " " * len(m.group(3)))
return "$%s$" % m.group(1)
keywords = [keyword
for name in keyword_str.split(" ")
for keyword in svn_keywords.get(name, [])]
return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content)
def GetUnknownFiles(self):
status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True)
unknown_files = []
for line in status.split("\n"):
if line and line[0] == "?":
unknown_files.append(line)
return unknown_files
def ReadFile(self, filename):
"""Returns the contents of a file."""
file = open(filename, 'rb')
result = ""
try:
result = file.read()
finally:
file.close()
return result
def GetStatus(self, filename):
"""Returns the status of a file."""
if not self.options.revision:
status = RunShell(["svn", "status", "--ignore-externals", filename])
if not status:
ErrorExit("svn status returned no output for %s" % filename)
status_lines = status.splitlines()
# If file is in a cl, the output will begin with
# "\n--- Changelist 'cl_name':\n". See
# http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt
if (len(status_lines) == 3 and
not status_lines[0] and
status_lines[1].startswith("--- Changelist")):
status = status_lines[2]
else:
status = status_lines[0]
# If we have a revision to diff against we need to run "svn list"
# for the old and the new revision and compare the results to get
# the correct status for a file.
else:
dirname, relfilename = os.path.split(filename)
if dirname not in self.svnls_cache:
cmd = ["svn", "list", "-r", self.rev_start, dirname or "."]
out, returncode = RunShellWithReturnCode(cmd)
if returncode:
ErrorExit("Failed to get status for %s." % filename)
old_files = out.splitlines()
args = ["svn", "list"]
if self.rev_end:
args += ["-r", self.rev_end]
cmd = args + [dirname or "."]
out, returncode = RunShellWithReturnCode(cmd)
if returncode:
ErrorExit("Failed to run command %s" % cmd)
self.svnls_cache[dirname] = (old_files, out.splitlines())
old_files, new_files = self.svnls_cache[dirname]
if relfilename in old_files and relfilename not in new_files:
status = "D "
elif relfilename in old_files and relfilename in new_files:
status = "M "
else:
status = "A "
return status
def GetBaseFile(self, filename):
status = self.GetStatus(filename)
base_content = None
new_content = None
# If a file is copied its status will be "A +", which signifies
# "addition-with-history". See "svn st" for more information. We need to
# upload the original file or else diff parsing will fail if the file was
# edited.
if status[0] == "A" and status[3] != "+":
# We'll need to upload the new content if we're adding a binary file
# since diff's output won't contain it.
mimetype = RunShell(["svn", "propget", "svn:mime-type", filename],
silent_ok=True)
base_content = ""
is_binary = mimetype and not mimetype.startswith("text/")
if is_binary and self.IsImage(filename):
new_content = self.ReadFile(filename)
elif (status[0] in ("M", "D", "R") or
(status[0] == "A" and status[3] == "+") or # Copied file.
(status[0] == " " and status[1] == "M")): # Property change.
args = []
if self.options.revision:
url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
else:
# Don't change filename, it's needed later.
url = filename
args += ["-r", "BASE"]
cmd = ["svn"] + args + ["propget", "svn:mime-type", url]
mimetype, returncode = RunShellWithReturnCode(cmd)
if returncode:
# File does not exist in the requested revision.
# Reset mimetype, it contains an error message.
mimetype = ""
get_base = False
is_binary = mimetype and not mimetype.startswith("text/")
if status[0] == " ":
# Empty base content just to force an upload.
base_content = ""
elif is_binary:
if self.IsImage(filename):
get_base = True
if status[0] == "M":
if not self.rev_end:
new_content = self.ReadFile(filename)
else:
url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end)
new_content = RunShell(["svn", "cat", url],
universal_newlines=True, silent_ok=True)
else:
base_content = ""
else:
get_base = True
if get_base:
if is_binary:
universal_newlines = False
else:
universal_newlines = True
if self.rev_start:
# "svn cat -r REV delete_file.txt" doesn't work. cat requires
# the full URL with "@REV" appended instead of using "-r" option.
url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
base_content = RunShell(["svn", "cat", url],
universal_newlines=universal_newlines,
silent_ok=True)
else:
base_content = RunShell(["svn", "cat", filename],
universal_newlines=universal_newlines,
silent_ok=True)
if not is_binary:
args = []
if self.rev_start:
url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
else:
url = filename
args += ["-r", "BASE"]
cmd = ["svn"] + args + ["propget", "svn:keywords", url]
keywords, returncode = RunShellWithReturnCode(cmd)
if keywords and not returncode:
base_content = self._CollapseKeywords(base_content, keywords)
else:
StatusUpdate("svn status returned unexpected output: %s" % status)
sys.exit(1)
return base_content, new_content, is_binary, status[0:5]
class GitVCS(VersionControlSystem):
"""Implementation of the VersionControlSystem interface for Git."""
def __init__(self, options):
super(GitVCS, self).__init__(options)
# Map of filename -> hash of base file.
self.base_hashes = {}
def GenerateDiff(self, extra_args):
# This is more complicated than svn's GenerateDiff because we must convert
# the diff output to include an svn-style "Index:" line as well as record
# the hashes of the base files, so we can upload them along with our diff.
if self.options.revision:
extra_args = [self.options.revision] + extra_args
gitdiff = RunShell(["git", "diff", "--full-index"] + extra_args)
svndiff = []
filecount = 0
filename = None
for line in gitdiff.splitlines():
match = re.match(r"diff --git a/(.*) b/.*$", line)
if match:
filecount += 1
filename = match.group(1)
svndiff.append("Index: %s\n" % filename)
else:
# The "index" line in a git diff looks like this (long hashes elided):
# index 82c0d44..b2cee3f 100755
# We want to save the left hash, as that identifies the base file.
match = re.match(r"index (\w+)\.\.", line)
if match:
self.base_hashes[filename] = match.group(1)
svndiff.append(line + "\n")
if not filecount:
ErrorExit("No valid patches found in output from git diff")
return "".join(svndiff)
def GetUnknownFiles(self):
status = RunShell(["git", "ls-files", "--exclude-standard", "--others"],
silent_ok=True)
return status.splitlines()
def GetBaseFile(self, filename):
hash = self.base_hashes[filename]
base_content = None
new_content = None
is_binary = False
if hash == "0" * 40: # All-zero hash indicates no base file.
status = "A"
base_content = ""
else:
status = "M"
base_content, returncode = RunShellWithReturnCode(["git", "show", hash])
if returncode:
ErrorExit("Got error status from 'git show %s'" % hash)
return (base_content, new_content, is_binary, status)
class MercurialVCS(VersionControlSystem):
"""Implementation of the VersionControlSystem interface for Mercurial."""
def __init__(self, options, repo_dir):
super(MercurialVCS, self).__init__(options)
# Absolute path to repository (we can be in a subdir)
self.repo_dir = os.path.normpath(repo_dir)
# Compute the subdir
cwd = os.path.normpath(os.getcwd())
assert cwd.startswith(self.repo_dir)
self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/")
if self.options.revision:
self.base_rev = self.options.revision
else:
self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip()
def _GetRelPath(self, filename):
"""Get relative path of a file according to the current directory,
given its logical path in the repo."""
assert filename.startswith(self.subdir), filename
return filename[len(self.subdir):].lstrip(r"\/")
def GenerateDiff(self, extra_args):
# If no file specified, restrict to the current subdir
extra_args = extra_args or ["."]
cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args
data = RunShell(cmd, silent_ok=True)
svndiff = []
filecount = 0
for line in data.splitlines():
m = re.match("diff --git a/(\S+) b/(\S+)", line)
if m:
# Modify line to make it look like as it comes from svn diff.
# With this modification no changes on the server side are required
# to make upload.py work with Mercurial repos.
# NOTE: for proper handling of moved/copied files, we have to use
# the second filename.
filename = m.group(2)
svndiff.append("Index: %s" % filename)
svndiff.append("=" * 67)
filecount += 1
logging.info(line)
else:
svndiff.append(line)
if not filecount:
ErrorExit("No valid patches found in output from hg diff")
return "\n".join(svndiff) + "\n"
def GetUnknownFiles(self):
"""Return a list of files unknown to the VCS."""
args = []
status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."],
silent_ok=True)
unknown_files = []
for line in status.splitlines():
st, fn = line.split(" ", 1)
if st == "?":
unknown_files.append(fn)
return unknown_files
def GetBaseFile(self, filename):
# "hg status" and "hg cat" both take a path relative to the current subdir
# rather than to the repo root, but "hg diff" has given us the full path
# to the repo root.
base_content = ""
new_content = None
is_binary = False
oldrelpath = relpath = self._GetRelPath(filename)
# "hg status -C" returns two lines for moved/copied files, one otherwise
out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath])
out = out.splitlines()
# HACK: strip error message about missing file/directory if it isn't in
# the working copy
if out[0].startswith('%s: ' % relpath):
out = out[1:]
if len(out) > 1:
# Moved/copied => considered as modified, use old filename to
# retrieve base contents
oldrelpath = out[1].strip()
status = "M"
else:
status, _ = out[0].split(' ', 1)
if status != "A":
base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath],
silent_ok=True)
is_binary = "\0" in base_content # Mercurial's heuristic
if status != "R":
new_content = open(relpath, "rb").read()
is_binary = is_binary or "\0" in new_content
if is_binary and base_content:
# Fetch again without converting newlines
base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath],
silent_ok=True, universal_newlines=False)
if not is_binary or not self.IsImage(relpath):
new_content = None
return base_content, new_content, is_binary, status
# NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync.
def SplitPatch(data):
"""Splits a patch into separate pieces for each file.
Args:
data: A string containing the output of svn diff.
Returns:
A list of 2-tuple (filename, text) where text is the svn diff output
pertaining to filename.
"""
patches = []
filename = None
diff = []
for line in data.splitlines(True):
new_filename = None
if line.startswith('Index:'):
unused, new_filename = line.split(':', 1)
new_filename = new_filename.strip()
elif line.startswith('Property changes on:'):
unused, temp_filename = line.split(':', 1)
# When a file is modified, paths use '/' between directories, however
# when a property is modified '\' is used on Windows. Make them the same
# otherwise the file shows up twice.
temp_filename = temp_filename.strip().replace('\\', '/')
if temp_filename != filename:
# File has property changes but no modifications, create a new diff.
new_filename = temp_filename
if new_filename:
if filename and diff:
patches.append((filename, ''.join(diff)))
filename = new_filename
diff = [line]
continue
if diff is not None:
diff.append(line)
if filename and diff:
patches.append((filename, ''.join(diff)))
return patches
def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
"""Uploads a separate patch for each file in the diff output.
Returns a list of [patch_key, filename] for each file.
"""
patches = SplitPatch(data)
rv = []
for patch in patches:
if len(patch[1]) > MAX_UPLOAD_SIZE:
print ("Not uploading the patch for " + patch[0] +
" because the file is too large.")
continue
form_fields = [("filename", patch[0])]
if not options.download_base:
form_fields.append(("content_upload", "1"))
files = [("data", "data.diff", patch[1])]
ctype, body = EncodeMultipartFormData(form_fields, files)
url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
print "Uploading patch for " + patch[0]
response_body = rpc_server.Send(url, body, content_type=ctype)
lines = response_body.splitlines()
if not lines or lines[0] != "OK":
StatusUpdate(" --> %s" % response_body)
sys.exit(1)
rv.append([lines[1], patch[0]])
return rv
def GuessVCS(options):
"""Helper to guess the version control system.
This examines the current directory, guesses which VersionControlSystem
we're using, and returns an instance of the appropriate class. Exit with an
error if we can't figure it out.
Returns:
A VersionControlSystem instance. Exits if the VCS can't be guessed.
"""
# Mercurial has a command to get the base directory of a repository
# Try running it, but don't die if we don't have hg installed.
# NOTE: we try Mercurial first as it can sit on top of an SVN working copy.
try:
out, returncode = RunShellWithReturnCode(["hg", "root"])
if returncode == 0:
return MercurialVCS(options, out.strip())
except OSError, (errno, message):
if errno != 2: # ENOENT -- they don't have hg installed.
raise
# Subversion has a .svn in all working directories.
if os.path.isdir('.svn'):
logging.info("Guessed VCS = Subversion")
return SubversionVCS(options)
# Git has a command to test if you're in a git tree.
# Try running it, but don't die if we don't have git installed.
try:
out, returncode = RunShellWithReturnCode(["git", "rev-parse",
"--is-inside-work-tree"])
if returncode == 0:
return GitVCS(options)
except OSError, (errno, message):
if errno != 2: # ENOENT -- they don't have git installed.
raise
ErrorExit(("Could not guess version control system. "
"Are you in a working copy directory?"))
def RealMain(argv, data=None):
"""The real main function.
Args:
argv: Command line arguments.
data: Diff contents. If None (default) the diff is generated by
the VersionControlSystem implementation returned by GuessVCS().
Returns:
A 2-tuple (issue id, patchset id).
The patchset id is None if the base files are not uploaded by this
script (applies only to SVN checkouts).
"""
logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:"
"%(lineno)s %(message)s "))
os.environ['LC_ALL'] = 'C'
options, args = parser.parse_args(argv[1:])
global verbosity
verbosity = options.verbose
if verbosity >= 3:
logging.getLogger().setLevel(logging.DEBUG)
elif verbosity >= 2:
logging.getLogger().setLevel(logging.INFO)
vcs = GuessVCS(options)
if isinstance(vcs, SubversionVCS):
# base field is only allowed for Subversion.
# Note: Fetching base files may become deprecated in future releases.
base = vcs.GuessBase(options.download_base)
else:
base = None
if not base and options.download_base:
options.download_base = True
logging.info("Enabled upload of base file")
if not options.assume_yes:
vcs.CheckForUnknownFiles()
if data is None:
data = vcs.GenerateDiff(args)
files = vcs.GetBaseFiles(data)
if verbosity >= 1:
print "Upload server:", options.server, "(change with -s/--server)"
if options.issue:
prompt = "Message describing this patch set: "
else:
prompt = "New issue subject: "
message = options.message or raw_input(prompt).strip()
if not message:
ErrorExit("A non-empty message is required")
rpc_server = GetRpcServer(options)
form_fields = [("subject", message)]
if base:
form_fields.append(("base", base))
if options.issue:
form_fields.append(("issue", str(options.issue)))
if options.email:
form_fields.append(("user", options.email))
if options.reviewers:
for reviewer in options.reviewers.split(','):
if "@" in reviewer and not reviewer.split("@")[1].count(".") == 1:
ErrorExit("Invalid email address: %s" % reviewer)
form_fields.append(("reviewers", options.reviewers))
if options.cc:
for cc in options.cc.split(','):
if "@" in cc and not cc.split("@")[1].count(".") == 1:
ErrorExit("Invalid email address: %s" % cc)
form_fields.append(("cc", options.cc))
description = options.description
if options.description_file:
if options.description:
ErrorExit("Can't specify description and description_file")
file = open(options.description_file, 'r')
description = file.read()
file.close()
if description:
form_fields.append(("description", description))
# Send a hash of all the base file so the server can determine if a copy
# already exists in an earlier patchset.
base_hashes = ""
for file, info in files.iteritems():
if not info[0] is None:
checksum = md5.new(info[0]).hexdigest()
if base_hashes:
base_hashes += "|"
base_hashes += checksum + ":" + file
form_fields.append(("base_hashes", base_hashes))
# If we're uploading base files, don't send the email before the uploads, so
# that it contains the file status.
if options.send_mail and options.download_base:
form_fields.append(("send_mail", "1"))
if not options.download_base:
form_fields.append(("content_upload", "1"))
if len(data) > MAX_UPLOAD_SIZE:
print "Patch is large, so uploading file patches separately."
uploaded_diff_file = []
form_fields.append(("separate_patches", "1"))
else:
uploaded_diff_file = [("data", "data.diff", data)]
ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file)
response_body = rpc_server.Send("/upload", body, content_type=ctype)
patchset = None
if not options.download_base or not uploaded_diff_file:
lines = response_body.splitlines()
if len(lines) >= 2:
msg = lines[0]
patchset = lines[1].strip()
patches = [x.split(" ", 1) for x in lines[2:]]
else:
msg = response_body
else:
msg = response_body
StatusUpdate(msg)
if not response_body.startswith("Issue created.") and \
not response_body.startswith("Issue updated."):
sys.exit(0)
issue = msg[msg.rfind("/")+1:]
if not uploaded_diff_file:
result = UploadSeparatePatches(issue, rpc_server, patchset, data, options)
if not options.download_base:
patches = result
if not options.download_base:
vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files)
if options.send_mail:
rpc_server.Send("/" + issue + "/mail", payload="")
return issue, patchset
def main():
try:
RealMain(sys.argv)
except KeyboardInterrupt:
print
StatusUpdate("Interrupted.")
sys.exit(1)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""pump v0.1 - Pretty Useful for Meta Programming.
A tool for preprocessor meta programming. Useful for generating
repetitive boilerplate code. Especially useful for writing C++
classes, functions, macros, and templates that need to work with
various number of arguments.
USAGE:
pump.py SOURCE_FILE
EXAMPLES:
pump.py foo.cc.pump
Converts foo.cc.pump to foo.cc.
GRAMMAR:
CODE ::= ATOMIC_CODE*
ATOMIC_CODE ::= $var ID = EXPRESSION
| $var ID = [[ CODE ]]
| $range ID EXPRESSION..EXPRESSION
| $for ID SEPARATOR [[ CODE ]]
| $($)
| $ID
| $(EXPRESSION)
| $if EXPRESSION [[ CODE ]] ELSE_BRANCH
| [[ CODE ]]
| RAW_CODE
SEPARATOR ::= RAW_CODE | EMPTY
ELSE_BRANCH ::= $else [[ CODE ]]
| $elif EXPRESSION [[ CODE ]] ELSE_BRANCH
| EMPTY
EXPRESSION has Python syntax.
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import re
import sys
TOKEN_TABLE = [
(re.compile(r'\$var\s+'), '$var'),
(re.compile(r'\$elif\s+'), '$elif'),
(re.compile(r'\$else\s+'), '$else'),
(re.compile(r'\$for\s+'), '$for'),
(re.compile(r'\$if\s+'), '$if'),
(re.compile(r'\$range\s+'), '$range'),
(re.compile(r'\$[_A-Za-z]\w*'), '$id'),
(re.compile(r'\$\(\$\)'), '$($)'),
(re.compile(r'\$\$.*'), '$$'),
(re.compile(r'\$'), '$'),
(re.compile(r'\[\[\n?'), '[['),
(re.compile(r'\]\]\n?'), ']]'),
]
class Cursor:
"""Represents a position (line and column) in a text file."""
def __init__(self, line=-1, column=-1):
self.line = line
self.column = column
def __eq__(self, rhs):
return self.line == rhs.line and self.column == rhs.column
def __ne__(self, rhs):
return not self == rhs
def __lt__(self, rhs):
return self.line < rhs.line or (
self.line == rhs.line and self.column < rhs.column)
def __le__(self, rhs):
return self < rhs or self == rhs
def __gt__(self, rhs):
return rhs < self
def __ge__(self, rhs):
return rhs <= self
def __str__(self):
if self == Eof():
return 'EOF'
else:
return '%s(%s)' % (self.line + 1, self.column)
def __add__(self, offset):
return Cursor(self.line, self.column + offset)
def __sub__(self, offset):
return Cursor(self.line, self.column - offset)
def Clone(self):
"""Returns a copy of self."""
return Cursor(self.line, self.column)
# Special cursor to indicate the end-of-file.
def Eof():
"""Returns the special cursor to denote the end-of-file."""
return Cursor(-1, -1)
class Token:
"""Represents a token in a Pump source file."""
def __init__(self, start=None, end=None, value=None, token_type=None):
if start is None:
self.start = Eof()
else:
self.start = start
if end is None:
self.end = Eof()
else:
self.end = end
self.value = value
self.token_type = token_type
def __str__(self):
return 'Token @%s: \'%s\' type=%s' % (
self.start, self.value, self.token_type)
def Clone(self):
"""Returns a copy of self."""
return Token(self.start.Clone(), self.end.Clone(), self.value,
self.token_type)
def StartsWith(lines, pos, string):
"""Returns True iff the given position in lines starts with 'string'."""
return lines[pos.line][pos.column:].startswith(string)
def FindFirstInLine(line, token_table):
best_match_start = -1
for (regex, token_type) in token_table:
m = regex.search(line)
if m:
# We found regex in lines
if best_match_start < 0 or m.start() < best_match_start:
best_match_start = m.start()
best_match_length = m.end() - m.start()
best_match_token_type = token_type
if best_match_start < 0:
return None
return (best_match_start, best_match_length, best_match_token_type)
def FindFirst(lines, token_table, cursor):
"""Finds the first occurrence of any string in strings in lines."""
start = cursor.Clone()
cur_line_number = cursor.line
for line in lines[start.line:]:
if cur_line_number == start.line:
line = line[start.column:]
m = FindFirstInLine(line, token_table)
if m:
# We found a regex in line.
(start_column, length, token_type) = m
if cur_line_number == start.line:
start_column += start.column
found_start = Cursor(cur_line_number, start_column)
found_end = found_start + length
return MakeToken(lines, found_start, found_end, token_type)
cur_line_number += 1
# We failed to find str in lines
return None
def SubString(lines, start, end):
"""Returns a substring in lines."""
if end == Eof():
end = Cursor(len(lines) - 1, len(lines[-1]))
if start >= end:
return ''
if start.line == end.line:
return lines[start.line][start.column:end.column]
result_lines = ([lines[start.line][start.column:]] +
lines[start.line + 1:end.line] +
[lines[end.line][:end.column]])
return ''.join(result_lines)
def MakeToken(lines, start, end, token_type):
"""Creates a new instance of Token."""
return Token(start, end, SubString(lines, start, end), token_type)
def ParseToken(lines, pos, regex, token_type):
line = lines[pos.line][pos.column:]
m = regex.search(line)
if m and not m.start():
return MakeToken(lines, pos, pos + m.end(), token_type)
else:
print 'ERROR: %s expected at %s.' % (token_type, pos)
sys.exit(1)
ID_REGEX = re.compile(r'[_A-Za-z]\w*')
EQ_REGEX = re.compile(r'=')
REST_OF_LINE_REGEX = re.compile(r'.*?(?=$|\$\$)')
OPTIONAL_WHITE_SPACES_REGEX = re.compile(r'\s*')
WHITE_SPACE_REGEX = re.compile(r'\s')
DOT_DOT_REGEX = re.compile(r'\.\.')
def Skip(lines, pos, regex):
line = lines[pos.line][pos.column:]
m = re.search(regex, line)
if m and not m.start():
return pos + m.end()
else:
return pos
def SkipUntil(lines, pos, regex, token_type):
line = lines[pos.line][pos.column:]
m = re.search(regex, line)
if m:
return pos + m.start()
else:
print ('ERROR: %s expected on line %s after column %s.' %
(token_type, pos.line + 1, pos.column))
sys.exit(1)
def ParseExpTokenInParens(lines, pos):
def ParseInParens(pos):
pos = Skip(lines, pos, OPTIONAL_WHITE_SPACES_REGEX)
pos = Skip(lines, pos, r'\(')
pos = Parse(pos)
pos = Skip(lines, pos, r'\)')
return pos
def Parse(pos):
pos = SkipUntil(lines, pos, r'\(|\)', ')')
if SubString(lines, pos, pos + 1) == '(':
pos = Parse(pos + 1)
pos = Skip(lines, pos, r'\)')
return Parse(pos)
else:
return pos
start = pos.Clone()
pos = ParseInParens(pos)
return MakeToken(lines, start, pos, 'exp')
def RStripNewLineFromToken(token):
if token.value.endswith('\n'):
return Token(token.start, token.end, token.value[:-1], token.token_type)
else:
return token
def TokenizeLines(lines, pos):
while True:
found = FindFirst(lines, TOKEN_TABLE, pos)
if not found:
yield MakeToken(lines, pos, Eof(), 'code')
return
if found.start == pos:
prev_token = None
prev_token_rstripped = None
else:
prev_token = MakeToken(lines, pos, found.start, 'code')
prev_token_rstripped = RStripNewLineFromToken(prev_token)
if found.token_type == '$$': # A meta comment.
if prev_token_rstripped:
yield prev_token_rstripped
pos = Cursor(found.end.line + 1, 0)
elif found.token_type == '$var':
if prev_token_rstripped:
yield prev_token_rstripped
yield found
id_token = ParseToken(lines, found.end, ID_REGEX, 'id')
yield id_token
pos = Skip(lines, id_token.end, OPTIONAL_WHITE_SPACES_REGEX)
eq_token = ParseToken(lines, pos, EQ_REGEX, '=')
yield eq_token
pos = Skip(lines, eq_token.end, r'\s*')
if SubString(lines, pos, pos + 2) != '[[':
exp_token = ParseToken(lines, pos, REST_OF_LINE_REGEX, 'exp')
yield exp_token
pos = Cursor(exp_token.end.line + 1, 0)
elif found.token_type == '$for':
if prev_token_rstripped:
yield prev_token_rstripped
yield found
id_token = ParseToken(lines, found.end, ID_REGEX, 'id')
yield id_token
pos = Skip(lines, id_token.end, WHITE_SPACE_REGEX)
elif found.token_type == '$range':
if prev_token_rstripped:
yield prev_token_rstripped
yield found
id_token = ParseToken(lines, found.end, ID_REGEX, 'id')
yield id_token
pos = Skip(lines, id_token.end, OPTIONAL_WHITE_SPACES_REGEX)
dots_pos = SkipUntil(lines, pos, DOT_DOT_REGEX, '..')
yield MakeToken(lines, pos, dots_pos, 'exp')
yield MakeToken(lines, dots_pos, dots_pos + 2, '..')
pos = dots_pos + 2
new_pos = Cursor(pos.line + 1, 0)
yield MakeToken(lines, pos, new_pos, 'exp')
pos = new_pos
elif found.token_type == '$':
if prev_token:
yield prev_token
yield found
exp_token = ParseExpTokenInParens(lines, found.end)
yield exp_token
pos = exp_token.end
elif (found.token_type == ']]' or found.token_type == '$if' or
found.token_type == '$elif' or found.token_type == '$else'):
if prev_token_rstripped:
yield prev_token_rstripped
yield found
pos = found.end
else:
if prev_token:
yield prev_token
yield found
pos = found.end
def Tokenize(s):
lines = s.splitlines(True)
return TokenizeLines(lines, Cursor(0, 0))
class CodeNode:
def __init__(self, atomic_code_list=None):
self.atomic_code = atomic_code_list
class VarNode:
def __init__(self, identifier=None, atomic_code=None):
self.identifier = identifier
self.atomic_code = atomic_code
class RangeNode:
def __init__(self, identifier=None, exp1=None, exp2=None):
self.identifier = identifier
self.exp1 = exp1
self.exp2 = exp2
class ForNode:
def __init__(self, identifier=None, sep=None, code=None):
self.identifier = identifier
self.sep = sep
self.code = code
class ElseNode:
def __init__(self, else_branch=None):
self.else_branch = else_branch
class IfNode:
def __init__(self, exp=None, then_branch=None, else_branch=None):
self.exp = exp
self.then_branch = then_branch
self.else_branch = else_branch
class RawCodeNode:
def __init__(self, token=None):
self.raw_code = token
class LiteralDollarNode:
def __init__(self, token):
self.token = token
class ExpNode:
def __init__(self, token, python_exp):
self.token = token
self.python_exp = python_exp
def PopFront(a_list):
head = a_list[0]
a_list[:1] = []
return head
def PushFront(a_list, elem):
a_list[:0] = [elem]
def PopToken(a_list, token_type=None):
token = PopFront(a_list)
if token_type is not None and token.token_type != token_type:
print 'ERROR: %s expected at %s' % (token_type, token.start)
print 'ERROR: %s found instead' % (token,)
sys.exit(1)
return token
def PeekToken(a_list):
if not a_list:
return None
return a_list[0]
def ParseExpNode(token):
python_exp = re.sub(r'([_A-Za-z]\w*)', r'self.GetValue("\1")', token.value)
return ExpNode(token, python_exp)
def ParseElseNode(tokens):
def Pop(token_type=None):
return PopToken(tokens, token_type)
next = PeekToken(tokens)
if not next:
return None
if next.token_type == '$else':
Pop('$else')
Pop('[[')
code_node = ParseCodeNode(tokens)
Pop(']]')
return code_node
elif next.token_type == '$elif':
Pop('$elif')
exp = Pop('code')
Pop('[[')
code_node = ParseCodeNode(tokens)
Pop(']]')
inner_else_node = ParseElseNode(tokens)
return CodeNode([IfNode(ParseExpNode(exp), code_node, inner_else_node)])
elif not next.value.strip():
Pop('code')
return ParseElseNode(tokens)
else:
return None
def ParseAtomicCodeNode(tokens):
def Pop(token_type=None):
return PopToken(tokens, token_type)
head = PopFront(tokens)
t = head.token_type
if t == 'code':
return RawCodeNode(head)
elif t == '$var':
id_token = Pop('id')
Pop('=')
next = PeekToken(tokens)
if next.token_type == 'exp':
exp_token = Pop()
return VarNode(id_token, ParseExpNode(exp_token))
Pop('[[')
code_node = ParseCodeNode(tokens)
Pop(']]')
return VarNode(id_token, code_node)
elif t == '$for':
id_token = Pop('id')
next_token = PeekToken(tokens)
if next_token.token_type == 'code':
sep_token = next_token
Pop('code')
else:
sep_token = None
Pop('[[')
code_node = ParseCodeNode(tokens)
Pop(']]')
return ForNode(id_token, sep_token, code_node)
elif t == '$if':
exp_token = Pop('code')
Pop('[[')
code_node = ParseCodeNode(tokens)
Pop(']]')
else_node = ParseElseNode(tokens)
return IfNode(ParseExpNode(exp_token), code_node, else_node)
elif t == '$range':
id_token = Pop('id')
exp1_token = Pop('exp')
Pop('..')
exp2_token = Pop('exp')
return RangeNode(id_token, ParseExpNode(exp1_token),
ParseExpNode(exp2_token))
elif t == '$id':
return ParseExpNode(Token(head.start + 1, head.end, head.value[1:], 'id'))
elif t == '$($)':
return LiteralDollarNode(head)
elif t == '$':
exp_token = Pop('exp')
return ParseExpNode(exp_token)
elif t == '[[':
code_node = ParseCodeNode(tokens)
Pop(']]')
return code_node
else:
PushFront(tokens, head)
return None
def ParseCodeNode(tokens):
atomic_code_list = []
while True:
if not tokens:
break
atomic_code_node = ParseAtomicCodeNode(tokens)
if atomic_code_node:
atomic_code_list.append(atomic_code_node)
else:
break
return CodeNode(atomic_code_list)
def Convert(file_path):
s = file(file_path, 'r').read()
tokens = []
for token in Tokenize(s):
tokens.append(token)
code_node = ParseCodeNode(tokens)
return code_node
class Env:
def __init__(self):
self.variables = []
self.ranges = []
def Clone(self):
clone = Env()
clone.variables = self.variables[:]
clone.ranges = self.ranges[:]
return clone
def PushVariable(self, var, value):
# If value looks like an int, store it as an int.
try:
int_value = int(value)
if ('%s' % int_value) == value:
value = int_value
except Exception:
pass
self.variables[:0] = [(var, value)]
def PopVariable(self):
self.variables[:1] = []
def PushRange(self, var, lower, upper):
self.ranges[:0] = [(var, lower, upper)]
def PopRange(self):
self.ranges[:1] = []
def GetValue(self, identifier):
for (var, value) in self.variables:
if identifier == var:
return value
print 'ERROR: meta variable %s is undefined.' % (identifier,)
sys.exit(1)
def EvalExp(self, exp):
try:
result = eval(exp.python_exp)
except Exception, e:
print 'ERROR: caught exception %s: %s' % (e.__class__.__name__, e)
print ('ERROR: failed to evaluate meta expression %s at %s' %
(exp.python_exp, exp.token.start))
sys.exit(1)
return result
def GetRange(self, identifier):
for (var, lower, upper) in self.ranges:
if identifier == var:
return (lower, upper)
print 'ERROR: range %s is undefined.' % (identifier,)
sys.exit(1)
class Output:
def __init__(self):
self.string = ''
def GetLastLine(self):
index = self.string.rfind('\n')
if index < 0:
return ''
return self.string[index + 1:]
def Append(self, s):
self.string += s
def RunAtomicCode(env, node, output):
if isinstance(node, VarNode):
identifier = node.identifier.value.strip()
result = Output()
RunAtomicCode(env.Clone(), node.atomic_code, result)
value = result.string
env.PushVariable(identifier, value)
elif isinstance(node, RangeNode):
identifier = node.identifier.value.strip()
lower = int(env.EvalExp(node.exp1))
upper = int(env.EvalExp(node.exp2))
env.PushRange(identifier, lower, upper)
elif isinstance(node, ForNode):
identifier = node.identifier.value.strip()
if node.sep is None:
sep = ''
else:
sep = node.sep.value
(lower, upper) = env.GetRange(identifier)
for i in range(lower, upper + 1):
new_env = env.Clone()
new_env.PushVariable(identifier, i)
RunCode(new_env, node.code, output)
if i != upper:
output.Append(sep)
elif isinstance(node, RawCodeNode):
output.Append(node.raw_code.value)
elif isinstance(node, IfNode):
cond = env.EvalExp(node.exp)
if cond:
RunCode(env.Clone(), node.then_branch, output)
elif node.else_branch is not None:
RunCode(env.Clone(), node.else_branch, output)
elif isinstance(node, ExpNode):
value = env.EvalExp(node)
output.Append('%s' % (value,))
elif isinstance(node, LiteralDollarNode):
output.Append('$')
elif isinstance(node, CodeNode):
RunCode(env.Clone(), node, output)
else:
print 'BAD'
print node
sys.exit(1)
def RunCode(env, code_node, output):
for atomic_code in code_node.atomic_code:
RunAtomicCode(env, atomic_code, output)
def IsComment(cur_line):
return '//' in cur_line
def IsInPreprocessorDirevative(prev_lines, cur_line):
if cur_line.lstrip().startswith('#'):
return True
return prev_lines != [] and prev_lines[-1].endswith('\\')
def WrapComment(line, output):
loc = line.find('//')
before_comment = line[:loc].rstrip()
if before_comment == '':
indent = loc
else:
output.append(before_comment)
indent = len(before_comment) - len(before_comment.lstrip())
prefix = indent*' ' + '// '
max_len = 80 - len(prefix)
comment = line[loc + 2:].strip()
segs = [seg for seg in re.split(r'(\w+\W*)', comment) if seg != '']
cur_line = ''
for seg in segs:
if len((cur_line + seg).rstrip()) < max_len:
cur_line += seg
else:
if cur_line.strip() != '':
output.append(prefix + cur_line.rstrip())
cur_line = seg.lstrip()
if cur_line.strip() != '':
output.append(prefix + cur_line.strip())
def WrapCode(line, line_concat, output):
indent = len(line) - len(line.lstrip())
prefix = indent*' ' # Prefix of the current line
max_len = 80 - indent - len(line_concat) # Maximum length of the current line
new_prefix = prefix + 4*' ' # Prefix of a continuation line
new_max_len = max_len - 4 # Maximum length of a continuation line
# Prefers to wrap a line after a ',' or ';'.
segs = [seg for seg in re.split(r'([^,;]+[,;]?)', line.strip()) if seg != '']
cur_line = '' # The current line without leading spaces.
for seg in segs:
# If the line is still too long, wrap at a space.
while cur_line == '' and len(seg.strip()) > max_len:
seg = seg.lstrip()
split_at = seg.rfind(' ', 0, max_len)
output.append(prefix + seg[:split_at].strip() + line_concat)
seg = seg[split_at + 1:]
prefix = new_prefix
max_len = new_max_len
if len((cur_line + seg).rstrip()) < max_len:
cur_line = (cur_line + seg).lstrip()
else:
output.append(prefix + cur_line.rstrip() + line_concat)
prefix = new_prefix
max_len = new_max_len
cur_line = seg.lstrip()
if cur_line.strip() != '':
output.append(prefix + cur_line.strip())
def WrapPreprocessorDirevative(line, output):
WrapCode(line, ' \\', output)
def WrapPlainCode(line, output):
WrapCode(line, '', output)
def IsHeaderGuardOrInclude(line):
return (re.match(r'^#(ifndef|define|endif\s*//)\s*[\w_]+\s*$', line) or
re.match(r'^#include\s', line))
def WrapLongLine(line, output):
line = line.rstrip()
if len(line) <= 80:
output.append(line)
elif IsComment(line):
if IsHeaderGuardOrInclude(line):
# The style guide made an exception to allow long header guard lines
# and includes.
output.append(line)
else:
WrapComment(line, output)
elif IsInPreprocessorDirevative(output, line):
if IsHeaderGuardOrInclude(line):
# The style guide made an exception to allow long header guard lines
# and includes.
output.append(line)
else:
WrapPreprocessorDirevative(line, output)
else:
WrapPlainCode(line, output)
def BeautifyCode(string):
lines = string.splitlines()
output = []
for line in lines:
WrapLongLine(line, output)
output2 = [line.rstrip() for line in output]
return '\n'.join(output2) + '\n'
def main(argv):
if len(argv) == 1:
print __doc__
sys.exit(1)
file_path = argv[-1]
ast = Convert(file_path)
output = Output()
RunCode(Env(), ast, output)
output_str = BeautifyCode(output.string)
if file_path.endswith('.pump'):
output_file_path = file_path[:-5]
else:
output_file_path = '-'
if output_file_path == '-':
print output_str,
else:
output_file = file(output_file_path, 'w')
output_file.write('// This file was GENERATED by command:\n')
output_file.write('// %s %s\n' %
(os.path.basename(__file__), os.path.basename(file_path)))
output_file.write('// DO NOT EDIT BY HAND!!!\n\n')
output_file.write(output_str)
output_file.close()
if __name__ == '__main__':
main(sys.argv)
| Python |
#!/usr/bin/env python
#
# Copyright 2009, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""fuse_gtest_files.py v0.2.0
Fuses Google Test source code into a .h file and a .cc file.
SYNOPSIS
fuse_gtest_files.py [GTEST_ROOT_DIR] OUTPUT_DIR
Scans GTEST_ROOT_DIR for Google Test source code, and generates
two files: OUTPUT_DIR/gtest/gtest.h and OUTPUT_DIR/gtest/gtest-all.cc.
Then you can build your tests by adding OUTPUT_DIR to the include
search path and linking with OUTPUT_DIR/gtest/gtest-all.cc. These
two files contain everything you need to use Google Test. Hence
you can "install" Google Test by copying them to wherever you want.
GTEST_ROOT_DIR can be omitted and defaults to the parent
directory of the directory holding this script.
EXAMPLES
./fuse_gtest_files.py fused_gtest
./fuse_gtest_files.py path/to/unpacked/gtest fused_gtest
This tool is experimental. In particular, it assumes that there is no
conditional inclusion of Google Test headers. Please report any
problems to googletestframework@googlegroups.com. You can read
http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide for
more information.
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import re
import sets
import sys
# We assume that this file is in the scripts/ directory in the Google
# Test root directory.
DEFAULT_GTEST_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
# Regex for matching '#include <gtest/...>'.
INCLUDE_GTEST_FILE_REGEX = re.compile(r'^\s*#\s*include\s*<(gtest/.+)>')
# Regex for matching '#include "src/..."'.
INCLUDE_SRC_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(src/.+)"')
# Where to find the source seed files.
GTEST_H_SEED = 'include/gtest/gtest.h'
GTEST_SPI_H_SEED = 'include/gtest/gtest-spi.h'
GTEST_ALL_CC_SEED = 'src/gtest-all.cc'
# Where to put the generated files.
GTEST_H_OUTPUT = 'gtest/gtest.h'
GTEST_ALL_CC_OUTPUT = 'gtest/gtest-all.cc'
def VerifyFileExists(directory, relative_path):
"""Verifies that the given file exists; aborts on failure.
relative_path is the file path relative to the given directory.
"""
if not os.path.isfile(os.path.join(directory, relative_path)):
print 'ERROR: Cannot find %s in directory %s.' % (relative_path,
directory)
print ('Please either specify a valid project root directory '
'or omit it on the command line.')
sys.exit(1)
def ValidateGTestRootDir(gtest_root):
"""Makes sure gtest_root points to a valid gtest root directory.
The function aborts the program on failure.
"""
VerifyFileExists(gtest_root, GTEST_H_SEED)
VerifyFileExists(gtest_root, GTEST_ALL_CC_SEED)
def VerifyOutputFile(output_dir, relative_path):
"""Verifies that the given output file path is valid.
relative_path is relative to the output_dir directory.
"""
# Makes sure the output file either doesn't exist or can be overwritten.
output_file = os.path.join(output_dir, relative_path)
if os.path.exists(output_file):
# TODO(wan@google.com): The following user-interaction doesn't
# work with automated processes. We should provide a way for the
# Makefile to force overwriting the files.
print ('%s already exists in directory %s - overwrite it? (y/N) ' %
(relative_path, output_dir))
answer = sys.stdin.readline().strip()
if answer not in ['y', 'Y']:
print 'ABORTED.'
sys.exit(1)
# Makes sure the directory holding the output file exists; creates
# it and all its ancestors if necessary.
parent_directory = os.path.dirname(output_file)
if not os.path.isdir(parent_directory):
os.makedirs(parent_directory)
def ValidateOutputDir(output_dir):
"""Makes sure output_dir points to a valid output directory.
The function aborts the program on failure.
"""
VerifyOutputFile(output_dir, GTEST_H_OUTPUT)
VerifyOutputFile(output_dir, GTEST_ALL_CC_OUTPUT)
def FuseGTestH(gtest_root, output_dir):
"""Scans folder gtest_root to generate gtest/gtest.h in output_dir."""
output_file = file(os.path.join(output_dir, GTEST_H_OUTPUT), 'w')
processed_files = sets.Set() # Holds all gtest headers we've processed.
def ProcessFile(gtest_header_path):
"""Processes the given gtest header file."""
# We don't process the same header twice.
if gtest_header_path in processed_files:
return
processed_files.add(gtest_header_path)
# Reads each line in the given gtest header.
for line in file(os.path.join(gtest_root, gtest_header_path), 'r'):
m = INCLUDE_GTEST_FILE_REGEX.match(line)
if m:
# It's '#include <gtest/...>' - let's process it recursively.
ProcessFile('include/' + m.group(1))
else:
# Otherwise we copy the line unchanged to the output file.
output_file.write(line)
ProcessFile(GTEST_H_SEED)
output_file.close()
def FuseGTestAllCcToFile(gtest_root, output_file):
"""Scans folder gtest_root to generate gtest/gtest-all.cc in output_file."""
processed_files = sets.Set()
def ProcessFile(gtest_source_file):
"""Processes the given gtest source file."""
# We don't process the same #included file twice.
if gtest_source_file in processed_files:
return
processed_files.add(gtest_source_file)
# Reads each line in the given gtest source file.
for line in file(os.path.join(gtest_root, gtest_source_file), 'r'):
m = INCLUDE_GTEST_FILE_REGEX.match(line)
if m:
if 'include/' + m.group(1) == GTEST_SPI_H_SEED:
# It's '#include <gtest/gtest-spi.h>'. This file is not
# #included by <gtest/gtest.h>, so we need to process it.
ProcessFile(GTEST_SPI_H_SEED)
else:
# It's '#include <gtest/foo.h>' where foo is not gtest-spi.
# We treat it as '#include <gtest/gtest.h>', as all other
# gtest headers are being fused into gtest.h and cannot be
# #included directly.
# There is no need to #include <gtest/gtest.h> more than once.
if not GTEST_H_SEED in processed_files:
processed_files.add(GTEST_H_SEED)
output_file.write('#include <%s>\n' % (GTEST_H_OUTPUT,))
else:
m = INCLUDE_SRC_FILE_REGEX.match(line)
if m:
# It's '#include "src/foo"' - let's process it recursively.
ProcessFile(m.group(1))
else:
output_file.write(line)
ProcessFile(GTEST_ALL_CC_SEED)
def FuseGTestAllCc(gtest_root, output_dir):
"""Scans folder gtest_root to generate gtest/gtest-all.cc in output_dir."""
output_file = file(os.path.join(output_dir, GTEST_ALL_CC_OUTPUT), 'w')
FuseGTestAllCcToFile(gtest_root, output_file)
output_file.close()
def FuseGTest(gtest_root, output_dir):
"""Fuses gtest.h and gtest-all.cc."""
ValidateGTestRootDir(gtest_root)
ValidateOutputDir(output_dir)
FuseGTestH(gtest_root, output_dir)
FuseGTestAllCc(gtest_root, output_dir)
def main():
argc = len(sys.argv)
if argc == 2:
# fuse_gtest_files.py OUTPUT_DIR
FuseGTest(DEFAULT_GTEST_ROOT_DIR, sys.argv[1])
elif argc == 3:
# fuse_gtest_files.py GTEST_ROOT_DIR OUTPUT_DIR
FuseGTest(sys.argv[1], sys.argv[2])
else:
print __doc__
sys.exit(1)
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
#
# Copyright 2009, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""upload_gtest.py v0.1.0 -- uploads a Google Test patch for review.
This simple wrapper passes all command line flags and
--cc=googletestframework@googlegroups.com to upload.py.
USAGE: upload_gtest.py [options for upload.py]
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import sys
CC_FLAG = '--cc='
GTEST_GROUP = 'googletestframework@googlegroups.com'
def main():
# Finds the path to upload.py, assuming it is in the same directory
# as this file.
my_dir = os.path.dirname(os.path.abspath(__file__))
upload_py_path = os.path.join(my_dir, 'upload.py')
# Adds Google Test discussion group to the cc line if it's not there
# already.
upload_py_argv = [upload_py_path]
found_cc_flag = False
for arg in sys.argv[1:]:
if arg.startswith(CC_FLAG):
found_cc_flag = True
cc_line = arg[len(CC_FLAG):]
cc_list = [addr for addr in cc_line.split(',') if addr]
if GTEST_GROUP not in cc_list:
cc_list.append(GTEST_GROUP)
upload_py_argv.append(CC_FLAG + ','.join(cc_list))
else:
upload_py_argv.append(arg)
if not found_cc_flag:
upload_py_argv.append(CC_FLAG + GTEST_GROUP)
# Invokes upload.py with the modified command line flags.
os.execv(upload_py_path, upload_py_argv)
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""gen_gtest_pred_impl.py v0.1
Generates the implementation of Google Test predicate assertions and
accompanying tests.
Usage:
gen_gtest_pred_impl.py MAX_ARITY
where MAX_ARITY is a positive integer.
The command generates the implementation of up-to MAX_ARITY-ary
predicate assertions, and writes it to file gtest_pred_impl.h in the
directory where the script is. It also generates the accompanying
unit test in file gtest_pred_impl_unittest.cc.
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import sys
import time
# Where this script is.
SCRIPT_DIR = os.path.dirname(sys.argv[0])
# Where to store the generated header.
HEADER = os.path.join(SCRIPT_DIR, '../include/gtest/gtest_pred_impl.h')
# Where to store the generated unit test.
UNIT_TEST = os.path.join(SCRIPT_DIR, '../test/gtest_pred_impl_unittest.cc')
def HeaderPreamble(n):
"""Returns the preamble for the header file.
Args:
n: the maximum arity of the predicate macros to be generated.
"""
# A map that defines the values used in the preamble template.
DEFS = {
'today' : time.strftime('%m/%d/%Y'),
'year' : time.strftime('%Y'),
'command' : '%s %s' % (os.path.basename(sys.argv[0]), n),
'n' : n
}
return (
"""// Copyright 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This file is AUTOMATICALLY GENERATED on %(today)s by command
// '%(command)s'. DO NOT EDIT BY HAND!
//
// Implements a family of generic predicate assertion macros.
#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
// Makes sure this header is not included before gtest.h.
#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
#error Do not include gtest_pred_impl.h directly. Include gtest.h instead.
#endif // GTEST_INCLUDE_GTEST_GTEST_H_
// This header implements a family of generic predicate assertion
// macros:
//
// ASSERT_PRED_FORMAT1(pred_format, v1)
// ASSERT_PRED_FORMAT2(pred_format, v1, v2)
// ...
//
// where pred_format is a function or functor that takes n (in the
// case of ASSERT_PRED_FORMATn) values and their source expression
// text, and returns a testing::AssertionResult. See the definition
// of ASSERT_EQ in gtest.h for an example.
//
// If you don't care about formatting, you can use the more
// restrictive version:
//
// ASSERT_PRED1(pred, v1)
// ASSERT_PRED2(pred, v1, v2)
// ...
//
// where pred is an n-ary function or functor that returns bool,
// and the values v1, v2, ..., must support the << operator for
// streaming to std::ostream.
//
// We also define the EXPECT_* variations.
//
// For now we only support predicates whose arity is at most %(n)s.
// Please email googletestframework@googlegroups.com if you need
// support for higher arities.
// GTEST_ASSERT_ is the basic statement to which all of the assertions
// in this file reduce. Don't use this in your code.
#define GTEST_ASSERT_(expression, on_failure) \\
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \\
if (const ::testing::AssertionResult gtest_ar = (expression)) \\
; \\
else \\
on_failure(gtest_ar.failure_message())
""" % DEFS)
def Arity(n):
"""Returns the English name of the given arity."""
if n < 0:
return None
elif n <= 3:
return ['nullary', 'unary', 'binary', 'ternary'][n]
else:
return '%s-ary' % n
def Title(word):
"""Returns the given word in title case. The difference between
this and string's title() method is that Title('4-ary') is '4-ary'
while '4-ary'.title() is '4-Ary'."""
return word[0].upper() + word[1:]
def OneTo(n):
"""Returns the list [1, 2, 3, ..., n]."""
return range(1, n + 1)
def Iter(n, format, sep=''):
"""Given a positive integer n, a format string that contains 0 or
more '%s' format specs, and optionally a separator string, returns
the join of n strings, each formatted with the format string on an
iterator ranged from 1 to n.
Example:
Iter(3, 'v%s', sep=', ') returns 'v1, v2, v3'.
"""
# How many '%s' specs are in format?
spec_count = len(format.split('%s')) - 1
return sep.join([format % (spec_count * (i,)) for i in OneTo(n)])
def ImplementationForArity(n):
"""Returns the implementation of n-ary predicate assertions."""
# A map the defines the values used in the implementation template.
DEFS = {
'n' : str(n),
'vs' : Iter(n, 'v%s', sep=', '),
'vts' : Iter(n, '#v%s', sep=', '),
'arity' : Arity(n),
'Arity' : Title(Arity(n))
}
impl = """
// Helper function for implementing {EXPECT|ASSERT}_PRED%(n)s. Don't use
// this in your code.
template <typename Pred""" % DEFS
impl += Iter(n, """,
typename T%s""")
impl += """>
AssertionResult AssertPred%(n)sHelper(const char* pred_text""" % DEFS
impl += Iter(n, """,
const char* e%s""")
impl += """,
Pred pred"""
impl += Iter(n, """,
const T%s& v%s""")
impl += """) {
if (pred(%(vs)s)) return AssertionSuccess();
Message msg;
""" % DEFS
impl += ' msg << pred_text << "("'
impl += Iter(n, """
<< e%s""", sep=' << ", "')
impl += ' << ") evaluates to false, where"'
impl += Iter(n, """
<< "\\n" << e%s << " evaluates to " << v%s""")
impl += """;
return AssertionFailure(msg);
}
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
// Don't use this in your code.
#define GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, on_failure)\\
GTEST_ASSERT_(pred_format(%(vts)s, %(vs)s),\\
on_failure)
// Internal macro for implementing {EXPECT|ASSERT}_PRED%(n)s. Don't use
// this in your code.
#define GTEST_PRED%(n)s_(pred, %(vs)s, on_failure)\\
GTEST_ASSERT_(::testing::AssertPred%(n)sHelper(#pred""" % DEFS
impl += Iter(n, """, \\
#v%s""")
impl += """, \\
pred"""
impl += Iter(n, """, \\
v%s""")
impl += """), on_failure)
// %(Arity)s predicate assertion macros.
#define EXPECT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_NONFATAL_FAILURE_)
#define EXPECT_PRED%(n)s(pred, %(vs)s) \\
GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_NONFATAL_FAILURE_)
#define ASSERT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_FATAL_FAILURE_)
#define ASSERT_PRED%(n)s(pred, %(vs)s) \\
GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_FATAL_FAILURE_)
""" % DEFS
return impl
def HeaderPostamble():
"""Returns the postamble for the header file."""
return """
#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
"""
def GenerateFile(path, content):
"""Given a file path and a content string, overwrites it with the
given content."""
print 'Updating file %s . . .' % path
f = file(path, 'w+')
print >>f, content,
f.close()
print 'File %s has been updated.' % path
def GenerateHeader(n):
"""Given the maximum arity n, updates the header file that implements
the predicate assertions."""
GenerateFile(HEADER,
HeaderPreamble(n)
+ ''.join([ImplementationForArity(i) for i in OneTo(n)])
+ HeaderPostamble())
def UnitTestPreamble():
"""Returns the preamble for the unit test file."""
# A map that defines the values used in the preamble template.
DEFS = {
'today' : time.strftime('%m/%d/%Y'),
'year' : time.strftime('%Y'),
'command' : '%s %s' % (os.path.basename(sys.argv[0]), sys.argv[1]),
}
return (
"""// Copyright 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This file is AUTOMATICALLY GENERATED on %(today)s by command
// '%(command)s'. DO NOT EDIT BY HAND!
// Regression test for gtest_pred_impl.h
//
// This file is generated by a script and quite long. If you intend to
// learn how Google Test works by reading its unit tests, read
// gtest_unittest.cc instead.
//
// This is intended as a regression test for the Google Test predicate
// assertions. We compile it as part of the gtest_unittest target
// only to keep the implementation tidy and compact, as it is quite
// involved to set up the stage for testing Google Test using Google
// Test itself.
//
// Currently, gtest_unittest takes ~11 seconds to run in the testing
// daemon. In the future, if it grows too large and needs much more
// time to finish, we should consider separating this file into a
// stand-alone regression test.
#include <iostream>
#include <gtest/gtest.h>
#include <gtest/gtest-spi.h>
// A user-defined data type.
struct Bool {
explicit Bool(int val) : value(val != 0) {}
bool operator>(int n) const { return value > Bool(n).value; }
Bool operator+(const Bool& rhs) const { return Bool(value + rhs.value); }
bool operator==(const Bool& rhs) const { return value == rhs.value; }
bool value;
};
// Enables Bool to be used in assertions.
std::ostream& operator<<(std::ostream& os, const Bool& x) {
return os << (x.value ? "true" : "false");
}
""" % DEFS)
def TestsForArity(n):
"""Returns the tests for n-ary predicate assertions."""
# A map that defines the values used in the template for the tests.
DEFS = {
'n' : n,
'es' : Iter(n, 'e%s', sep=', '),
'vs' : Iter(n, 'v%s', sep=', '),
'vts' : Iter(n, '#v%s', sep=', '),
'tvs' : Iter(n, 'T%s v%s', sep=', '),
'int_vs' : Iter(n, 'int v%s', sep=', '),
'Bool_vs' : Iter(n, 'Bool v%s', sep=', '),
'types' : Iter(n, 'typename T%s', sep=', '),
'v_sum' : Iter(n, 'v%s', sep=' + '),
'arity' : Arity(n),
'Arity' : Title(Arity(n)),
}
tests = (
"""// Sample functions/functors for testing %(arity)s predicate assertions.
// A %(arity)s predicate function.
template <%(types)s>
bool PredFunction%(n)s(%(tvs)s) {
return %(v_sum)s > 0;
}
// The following two functions are needed to circumvent a bug in
// gcc 2.95.3, which sometimes has problem with the above template
// function.
bool PredFunction%(n)sInt(%(int_vs)s) {
return %(v_sum)s > 0;
}
bool PredFunction%(n)sBool(%(Bool_vs)s) {
return %(v_sum)s > 0;
}
""" % DEFS)
tests += """
// A %(arity)s predicate functor.
struct PredFunctor%(n)s {
template <%(types)s>
bool operator()(""" % DEFS
tests += Iter(n, 'const T%s& v%s', sep=""",
""")
tests += """) {
return %(v_sum)s > 0;
}
};
""" % DEFS
tests += """
// A %(arity)s predicate-formatter function.
template <%(types)s>
testing::AssertionResult PredFormatFunction%(n)s(""" % DEFS
tests += Iter(n, 'const char* e%s', sep=""",
""")
tests += Iter(n, """,
const T%s& v%s""")
tests += """) {
if (PredFunction%(n)s(%(vs)s))
return testing::AssertionSuccess();
testing::Message msg;
msg << """ % DEFS
tests += Iter(n, 'e%s', sep=' << " + " << ')
tests += """
<< " is expected to be positive, but evaluates to "
<< %(v_sum)s << ".";
return testing::AssertionFailure(msg);
}
""" % DEFS
tests += """
// A %(arity)s predicate-formatter functor.
struct PredFormatFunctor%(n)s {
template <%(types)s>
testing::AssertionResult operator()(""" % DEFS
tests += Iter(n, 'const char* e%s', sep=""",
""")
tests += Iter(n, """,
const T%s& v%s""")
tests += """) const {
return PredFormatFunction%(n)s(%(es)s, %(vs)s);
}
};
""" % DEFS
tests += """
// Tests for {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
class Predicate%(n)sTest : public testing::Test {
protected:
virtual void SetUp() {
expected_to_finish_ = true;
finished_ = false;""" % DEFS
tests += """
""" + Iter(n, 'n%s_ = ') + """0;
}
"""
tests += """
virtual void TearDown() {
// Verifies that each of the predicate's arguments was evaluated
// exactly once."""
tests += ''.join(["""
EXPECT_EQ(1, n%s_) <<
"The predicate assertion didn't evaluate argument %s "
"exactly once.";""" % (i, i + 1) for i in OneTo(n)])
tests += """
// Verifies that the control flow in the test function is expected.
if (expected_to_finish_ && !finished_) {
FAIL() << "The predicate assertion unexpactedly aborted the test.";
} else if (!expected_to_finish_ && finished_) {
FAIL() << "The failed predicate assertion didn't abort the test "
"as expected.";
}
}
// true iff the test function is expected to run to finish.
static bool expected_to_finish_;
// true iff the test function did run to finish.
static bool finished_;
""" % DEFS
tests += Iter(n, """
static int n%s_;""")
tests += """
};
bool Predicate%(n)sTest::expected_to_finish_;
bool Predicate%(n)sTest::finished_;
""" % DEFS
tests += Iter(n, """int Predicate%%(n)sTest::n%s_;
""") % DEFS
tests += """
typedef Predicate%(n)sTest EXPECT_PRED_FORMAT%(n)sTest;
typedef Predicate%(n)sTest ASSERT_PRED_FORMAT%(n)sTest;
typedef Predicate%(n)sTest EXPECT_PRED%(n)sTest;
typedef Predicate%(n)sTest ASSERT_PRED%(n)sTest;
""" % DEFS
def GenTest(use_format, use_assert, expect_failure,
use_functor, use_user_type):
"""Returns the test for a predicate assertion macro.
Args:
use_format: true iff the assertion is a *_PRED_FORMAT*.
use_assert: true iff the assertion is a ASSERT_*.
expect_failure: true iff the assertion is expected to fail.
use_functor: true iff the first argument of the assertion is
a functor (as opposed to a function)
use_user_type: true iff the predicate functor/function takes
argument(s) of a user-defined type.
Example:
GenTest(1, 0, 0, 1, 0) returns a test that tests the behavior
of a successful EXPECT_PRED_FORMATn() that takes a functor
whose arguments have built-in types."""
if use_assert:
assrt = 'ASSERT' # 'assert' is reserved, so we cannot use
# that identifier here.
else:
assrt = 'EXPECT'
assertion = assrt + '_PRED'
if use_format:
pred_format = 'PredFormat'
assertion += '_FORMAT'
else:
pred_format = 'Pred'
assertion += '%(n)s' % DEFS
if use_functor:
pred_format_type = 'functor'
pred_format += 'Functor%(n)s()'
else:
pred_format_type = 'function'
pred_format += 'Function%(n)s'
if not use_format:
if use_user_type:
pred_format += 'Bool'
else:
pred_format += 'Int'
test_name = pred_format_type.title()
if use_user_type:
arg_type = 'user-defined type (Bool)'
test_name += 'OnUserType'
if expect_failure:
arg = 'Bool(n%s_++)'
else:
arg = 'Bool(++n%s_)'
else:
arg_type = 'built-in type (int)'
test_name += 'OnBuiltInType'
if expect_failure:
arg = 'n%s_++'
else:
arg = '++n%s_'
if expect_failure:
successful_or_failed = 'failed'
expected_or_not = 'expected.'
test_name += 'Failure'
else:
successful_or_failed = 'successful'
expected_or_not = 'UNEXPECTED!'
test_name += 'Success'
# A map that defines the values used in the test template.
defs = DEFS.copy()
defs.update({
'assert' : assrt,
'assertion' : assertion,
'test_name' : test_name,
'pf_type' : pred_format_type,
'pf' : pred_format,
'arg_type' : arg_type,
'arg' : arg,
'successful' : successful_or_failed,
'expected' : expected_or_not,
})
test = """
// Tests a %(successful)s %(assertion)s where the
// predicate-formatter is a %(pf_type)s on a %(arg_type)s.
TEST_F(%(assertion)sTest, %(test_name)s) {""" % defs
indent = (len(assertion) + 3)*' '
extra_indent = ''
if expect_failure:
extra_indent = ' '
if use_assert:
test += """
expected_to_finish_ = false;
EXPECT_FATAL_FAILURE({ // NOLINT"""
else:
test += """
EXPECT_NONFATAL_FAILURE({ // NOLINT"""
test += '\n' + extra_indent + """ %(assertion)s(%(pf)s""" % defs
test = test % defs
test += Iter(n, ',\n' + indent + extra_indent + '%(arg)s' % defs)
test += ');\n' + extra_indent + ' finished_ = true;\n'
if expect_failure:
test += ' }, "");\n'
test += '}\n'
return test
# Generates tests for all 2**6 = 64 combinations.
tests += ''.join([GenTest(use_format, use_assert, expect_failure,
use_functor, use_user_type)
for use_format in [0, 1]
for use_assert in [0, 1]
for expect_failure in [0, 1]
for use_functor in [0, 1]
for use_user_type in [0, 1]
])
return tests
def UnitTestPostamble():
"""Returns the postamble for the tests."""
return ''
def GenerateUnitTest(n):
"""Returns the tests for up-to n-ary predicate assertions."""
GenerateFile(UNIT_TEST,
UnitTestPreamble()
+ ''.join([TestsForArity(i) for i in OneTo(n)])
+ UnitTestPostamble())
def _Main():
"""The entry point of the script. Generates the header file and its
unit test."""
if len(sys.argv) != 2:
print __doc__
print 'Author: ' + __author__
sys.exit(1)
n = int(sys.argv[1])
GenerateHeader(n)
GenerateUnitTest(n)
if __name__ == '__main__':
_Main()
| Python |
#!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""A script to prepare version informtion for use the gtest Info.plist file.
This script extracts the version information from the configure.ac file and
uses it to generate a header file containing the same information. The
#defines in this header file will be included in during the generation of
the Info.plist of the framework, giving the correct value to the version
shown in the Finder.
This script makes the following assumptions (these are faults of the script,
not problems with the Autoconf):
1. The AC_INIT macro will be contained within the first 1024 characters
of configure.ac
2. The version string will be 3 integers separated by periods and will be
surrounded by squre brackets, "[" and "]" (e.g. [1.0.1]). The first
segment represents the major version, the second represents the minor
version and the third represents the fix version.
3. No ")" character exists between the opening "(" and closing ")" of
AC_INIT, including in comments and character strings.
"""
import sys
import re
# Read the command line argument (the output directory for Version.h)
if (len(sys.argv) < 3):
print "Usage: versiongenerate.py input_dir output_dir"
sys.exit(1)
else:
input_dir = sys.argv[1]
output_dir = sys.argv[2]
# Read the first 1024 characters of the configure.ac file
config_file = open("%s/configure.ac" % input_dir, 'r')
buffer_size = 1024
opening_string = config_file.read(buffer_size)
config_file.close()
# Extract the version string from the AC_INIT macro
# The following init_expression means:
# Extract three integers separated by periods and surrounded by squre
# brackets(e.g. "[1.0.1]") between "AC_INIT(" and ")". Do not be greedy
# (*? is the non-greedy flag) since that would pull in everything between
# the first "(" and the last ")" in the file.
version_expression = re.compile(r"AC_INIT\(.*?\[(\d+)\.(\d+)\.(\d+)\].*?\)",
re.DOTALL)
version_values = version_expression.search(opening_string)
major_version = version_values.group(1)
minor_version = version_values.group(2)
fix_version = version_values.group(3)
# Write the version information to a header file to be included in the
# Info.plist file.
file_data = """//
// DO NOT MODIFY THIS FILE (but you can delete it)
//
// This file is autogenerated by the versiongenerate.py script. This script
// is executed in a "Run Script" build phase when creating gtest.framework. This
// header file is not used during compilation of C-source. Rather, it simply
// defines some version strings for substitution in the Info.plist. Because of
// this, we are not not restricted to C-syntax nor are we using include guards.
//
#define GTEST_VERSIONINFO_SHORT %s.%s
#define GTEST_VERSIONINFO_LONG %s.%s.%s
""" % (major_version, minor_version, major_version, minor_version, fix_version)
version_file = open("%s/Version.h" % output_dir, 'w')
version_file.write(file_data)
version_file.close()
| Python |
from relax import *
from tryy import *
from cycles import *
from cost_matrix import *
from graph import *
import networkx as nx
B = lecture("villes.txt") #coordonnees des points
M = fill_distance_matrix(B) #matrice des couts entre deux villes i et j
L = enumerer_cycles(len(B)) #liste des cycles
C = recherche_cout(L, M) #L liste des cycles, M matrice des couts
Sol = []
V = []
for s in range(len(B)):
if not s in V:
c = cycle_minimum(s, L, C)
Sol.append(c)
for sommet in c[0]:
if not sommet in V:
V.append(sommet)
relaxation(L, C, M, c[0])
print Sol
G = dessin_graph(Sol, B)
nx.draw(G)
nx.write_dot(G, "graph.dot")
plt.show()
| Python |
def relaxation(L, C, M, c):
i = 0
for cycle in L:
for k in range(len(c)):
for l in range(len(cycle)):
if c[k] == cycle[l] and c[(k+1)%len(c)] == cycle[(l-1)%len(cycle)]:
C[i] -= M[c[k]][c[(k+1)%len(c)]]
i += 1
| Python |
import numpy as np
import matplotlib.pyplot as mp
import math as ma
def distance(a,b,B):
return ma.sqrt(((B[b][0]-B[a][0])*(B[b][0]-B[a][0]))+((B[b][1]-B[a][1])*(B[b][1]-B[a][1])))
def fill_distance_matrix(T):
n = len(T)
M = np.zeros((n,n))
for i in np.arange(0,n):
for j in np.arange(i,n):
M[i][j] = distance(i, j, T)
M[j][i] = M[i,j]
return M
#def distance_euclidienne(x,y,u,v):
# return sqrt( (x-u)**2 + (y-v)**2)
#renvoie le tableau des couts du cycle reference par L[i]
def recherche_cout(L, M): #L liste des cycles, M matrice des couts
#n = M.shape[0] #nb de sommets
C = np.zeros(len(L))
i = 0
for s in L: #s est un des cycles de L
for j in np.arange(0, len(s)): #iteration sur les elements de s
a = s[j]
b = s[(j+1)%len(s)] #b est l'element apres a dans le cycle, donc le premier si a est le dernier
C[i] += M[a][b] #somme partielle des couts de M
i+=1
return C
def cycle_minimum(s, L, C):
cout_minimum = C[0]
cycle_min = L[0]
i = 0
for c in L:
if s in c:
if C[i] < cout_minimum:
cycle_min = c
cout_minimum = C[i]
i += 1
return (cycle_min, cout_minimum)
#print les sommets
#B = lecture("nodes.txt") #coordonnees des points
#M = fill_distance_matrix(B) #matrice symetrique des couts entre deux villes i et j
#L = enumerer_cycles(len(B)) #liste des cycles
#S = relaxation(L,M) #liste des arretes solution par algo set cover
#print sommets et arretes solution
#print M
#L=[ [1,6,17,2,13], [7,12,9,13,25], [16,3,24,10,18], [5, 29, 15, 3], [4,14,27,22], [20,2,19,21,8,14]]
#C=[8, 6, 27, 8, 9, 5]
#print recherche_cout(L,M)
#print cycle_minimum(14, L, C)
| Python |
import numpy as np
import matplotlib.pyplot as mp
import math as ma
def lecture(source):
test = open(source,"r")
k = 0
B = []
for ligne in test:
debut = ligne.rstrip('\n\r').split(" ")
B.append([int(debut[1]),int(debut[2]),debut[0]])
k = k+1
pass
test.close()
return B
def distance(a,b,B):
return ma.sqrt(((B[b][0]-B[a][0])*(B[b][0]-B[a][0]))+((B[b][1]-B[a][1])*(B[b][1]-B[a][1])))
| Python |
import math
def filtre(P, a, b):
s = []
for p in P:
if len(p) >= a and len(p) <= b:
s.append(p)
return s
def permutation(k, L):
pL = list(L)
fact = 1
i = 2
while i < len(L) + 1:
fact = fact * (i-1)
pos = i - ((k/fact) % i) - 1
swap = pL[pos]
pL[pos] = pL[i-1]
pL[i-1] = swap
i += 1
return pL
def permutations(L):
p = []
n = math.factorial(len(L))
i = 0
while i < n:
p.append(permutation(i, L))
i += 1
return p
def permut3(L):
p = []
p.append(L[2])
p.append(L[0])
p.append(L[1])
return p
def permuts3(L):
P = []
P.append(L)
a = permut3(L)
P.append(a)
b = permut3(a)
P.append(b)
return P
def Cnp(L, n,p, l=None, res=None):
""" Created: 2005.11.05 - Updated:
Calcul du Cnp - ne pas renseigne l et res lors de l'appel """
if l is None: l=[]
if res is None: res=[]
if p==0:
res.append(l)
return
if n==0: return
l1=list(l)
l1.append(L[n-1])
Cnp(L, n-1, p-1, l1, res)
Cnp(L, n-1, p, l, res)
return res
def cycles(Combis):
Cycles = []
for combi in Combis:
if len(combi) == 3:
cycle = combi
Cycles.append(cycle)
elif len(combi) == 4:
for perm in permuts3(combi[1:]):
cycle = []
cycle.append(combi[0])
cycle.extend(perm)
Cycles.append(cycle)
else:
for c in Cnp(combi[1:], len(combi[1:]), len(combi) - 4):
for p in permutations(c):
cycle = []
cycle.append(combi[0])
cycle.extend(p)
circ = []
for i in combi[1:]:
if not i in c:
circ.append(i)
for pp in permuts3(circ):
cycle2 = list(cycle)
cycle2.extend(pp)
Cycles.append(cycle2)
return Cycles
def combi(n, a, b):
C = []
i = 0
for i in range(a, b+1):
for c in Cnp(range(n), n, i):
C.append(c)
return C
def enumerer_cycles(n):
return cycles(combi(n, 4, 7))
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main()) | Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main()) | Python |
#!/usr/bin/env python
import sys,os
from subprocess import Popen,PIPE,call
import re,string
INTF="wlan0"
def runCmd(cmd):
retcode = call(string.join(cmd, " "), shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
sys.exit(1)
elif retcode!=0:
print >>sys.stderr, "Child returned", retcode
sys.exit(1)
if os.getuid()!=0:
print >>sys.stderr, "Not enough privilidges"
sys.exit(1)
print "Detecting AR Drone"
runCmd(["/sbin/ifconfig", INTF ,"up"])
scanres = Popen(["/sbin/iwlist", INTF, "scan"], stdout=PIPE).communicate()[0]
SSID=None
cells = re.split(r'\s+Cell [0-9]+',scanres)
for c in cells:
m = re.search(r'\s+ESSID\:"(ardrone_[0-9]+)',c)
if m:
SSID=m.group(1)
m = re.search(r'\s+Channel\:([0-9]+)',c)
if not m:
print >>sys.stderr, "Could not detect channel!"
sys.exit(1)
CHANNEL = m.group(1)
break
if SSID:
print "Found Ar.Drone with SSID %s on channel %s" % (SSID,CHANNEL)
else:
print >>sys.stderr, "Ar.Drone not found"
sys.exit(1)
print "Configuring WiFi interface"
runCmd(["/sbin/ifconfig", INTF ,"up"])
runCmd(["/sbin/iwconfig", INTF ,"mode","ad-hoc"])
runCmd(["/sbin/iwconfig", INTF ,"channel",str(CHANNEL)])
runCmd(["/sbin/iwconfig", INTF ,"Bit","54Mb/s"])
runCmd(["/sbin/iwconfig", INTF ,"essid",SSID])
print "Connecting to Ar.Drone"
runCmd(["/sbin/dhclient", INTF])
runCmd(["/sbin/route", "delete", "default", "gw", "192.168.1.1"])
print "Checking connectivity"
runCmd(["/bin/ping", "-c3", "192.168.1.1"])
print "Ar.Drone is ready with IP 192.168.1.1"
| Python |
# Run from the commandline:
#
# python server.py
# POST audio to http://localhost:9000
# GET audio from http://localhost:9000
#
# A simple server to collect audio using python. To be more secure,
# you might want to check the file names and place size restrictions
# on the incoming data.
import cgi
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class WamiHandler(BaseHTTPRequestHandler):
dirname = "/tmp/"
def do_GET(self):
f = open(self.get_name())
self.send_response(200)
self.send_header('content-type','audio/x-wav')
self.end_headers()
self.wfile.write(f.read())
f.close()
def do_POST(self):
f = open(self.get_name(), "wb")
# Note that python's HTTPServer doesn't support chunked transfer.
# Thus, it requires a content-length.
length = int(self.headers.getheader('content-length'))
print "POST of length " + str(length)
f.write(self.rfile.read(length))
f.close();
def get_name(self):
filename = 'output.wav';
qs = self.path.split('?',1);
if len(qs) == 2:
params = cgi.parse_qs(qs[1])
if params['name']:
filename = params['name'][0];
return WamiHandler.dirname + filename
def main():
try:
server = HTTPServer(('', 9000), WamiHandler)
print 'Started server...'
server.serve_forever()
except KeyboardInterrupt:
print 'Stopping server'
server.socket.close()
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
import glob, os
from distutils.core import setup
# FLOWBLADE distutils setup.py script.
install_data = [('share/applications', ['installdata/flowblade.desktop']),
('share/pixmaps', ['installdata/flowblade.png']),
('share/mime/packages',['installdata/flowblade.xml']),
('lib/mime/packages',['installdata/flowblade']),
('share/man/man1',['installdata/flowblade.1'])]
flowblade_package_data = ['res/filters/*.xml','res/filters/wipes/*','res/img/*',
'res/profiles/*','res/render/renderencoding.xml',
'res/patternproducer/*','res/help/*','locale/Flowblade/*',
'res/proxyprofiles/*','res/darktheme/*','launch/*']
locale_files = []
for filepath in glob.glob("Flowblade/locale/*/LC_MESSAGES/*"):
filepath = filepath.replace('Flowblade/', '')
locale_files.append(filepath)
setup( name='flowblade',
version='0.18.0',
author='Janne Liljeblad',
author_email='janne.liljeblad at gmail dot com',
description='Non-linear video editor',
url='http://code.google.com/p/flowblade/',
license='GNU GPL3',
scripts=['flowblade'],
packages=['Flowblade','Flowblade/tools','Flowblade/vieweditor'],
package_data={'Flowblade':flowblade_package_data + locale_files},
data_files=install_data)
| Python |
#!/usr/bin/env python
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import sys
print "FLOWBLADE MOVIE EDITOR 0.18"
print "---------------------------"
# Get launch script dir
launch_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
print "Launch script dir:", launch_dir
# Update sys.path to include modules
if launch_dir == "/usr/bin":
print "Running from installation..."
modules_path = "/usr/share/flowblade/Flowblade"
if not os.path.isdir(modules_path):
modules_path = "/usr/share/pyshared/Flowblade"
print "modules path:", modules_path
else:
print "Running from filesystem..."
modules_path = launch_dir + "/Flowblade"
sys.path.insert(0, modules_path)
sys.path.insert(0, modules_path + "/vieweditor")
sys.path.insert(0, modules_path + "/tools")
# Check that we have MLT, missing is fatal.
try:
import mlt
try:
mlt_version = mlt.LIBMLT_VERSION
print "MLT found, version:", mlt_version
except:
print "MLT found but version info not available. MLT probably too old to work reliably..."
except Exception, err:
print "MLT not found, exiting..."
print "ERROR:", err
sys.exit(1)
# Get app.py module and set info which type of installation is running
try:
import app
import editorstate
if launch_dir == "/usr/bin":
editorstate.app_running_from = editorstate.RUNNING_FROM_INSTALLATION
else:
editorstate.app_running_from = editorstate.RUNNING_FROM_DEV_VERSION
except Exception, err:
print "Failed to import module app.py to launch Flowblade!"
print "ERROR:", err
print "Installation was assumed to be at:", modules_path
sys.exit(1)
# Launch application
app.main(modules_path)
| Python |
#!/usr/bin/env python
import os, sys
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Script exracts params names from xml files into python code format for translation."
"""
script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
#source_file_path = script_dir + "/Flowblade/res/filters/filters.xml"
source_file_path = script_dir + "/Flowblade/res/filters/compositors.xml"
output_file_path = script_dir + "/params_trans_output"
# Read source
source_file = open(source_file_path)
source_text = source_file.read()
# Go through lines and build output
lines = source_text.splitlines()
out_lines = []
d_name_len = len("displayname=")
name_len = len("name=")
for line in lines:
if ((("property" in line) or ("multipartproperty" in line))
and (not("no_editor" in line))):
i = line.find("displayname=")
if i != -1:
start = i + d_name_len
else:
i = line.find("name=")
start = i + name_len + 1
e1 = line.find('"', start)
e2 = line.find(' ', start)
if e2 != -1 and (e2 < e1 ):
end = e2
else:
end = e1
param_name = line[start:end]
param_name = param_name.replace("!", " ")
out_line = ' param_names["' + param_name + '"] = _("' + param_name + '")\n'
out_lines.append(out_line)
out_str = "".join(out_lines)
# Write out
out_file = open(output_file_path,"w")
out_file.write(out_str)
out_file.close()
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module handles saving and loading data that is related to the editor and not any particular project.
"""
import pygtk
pygtk.require('2.0');
import gtk
import os
import pickle
import appconsts
import mltprofiles
import utils
PREFS_DOC = "prefs"
RECENT_DOC = "recent"
MAX_RECENT_PROJS = 15
UNDO_STACK_DEFAULT = 30
UNDO_STACK_MIN = 10
UNDO_STACK_MAX = 100
GLASS_STYLE = 0
SIMPLE_STYLE = 1
prefs = None
recent_projects = None
def load():
"""
If docs fail to load, new ones are created and saved.
"""
prefs_file_path = utils.get_hidden_user_dir_path() + PREFS_DOC
recents_file_path = utils.get_hidden_user_dir_path() + RECENT_DOC
global prefs, recent_projects
try:
f = open(prefs_file_path)
prefs = pickle.load(f)
except:
prefs = EditorPreferences()
write_file = file(prefs_file_path, "wb")
pickle.dump(prefs, write_file)
try:
f = open(recents_file_path)
recent_projects = pickle.load(f)
except:
recent_projects = utils.EmptyClass()
recent_projects.projects = []
write_file = file(recents_file_path, "wb")
pickle.dump(recent_projects, write_file)
# version of program may have different prefs objects and
# we may need to to update prefs on disk if user has e.g.
# installed later version of Flowblade
current_prefs = EditorPreferences()
if len(prefs.__dict__) != len(current_prefs.__dict__):
current_prefs.__dict__.update(prefs.__dict__)
prefs = current_prefs
write_file = file(prefs_file_path, "wb")
pickle.dump(prefs, write_file)
print "prefs updated to new version, new param count:", len(prefs.__dict__)
def save():
"""
Write out prefs and recent_projects files
"""
prefs_file_path = utils.get_hidden_user_dir_path() + PREFS_DOC
recents_file_path = utils.get_hidden_user_dir_path() + RECENT_DOC
write_file = file(prefs_file_path, "wb")
pickle.dump(prefs, write_file)
write_file = file(recents_file_path, "wb")
pickle.dump(recent_projects, write_file)
def add_recent_project_path(path):
"""
Called when project saved.
"""
if len(recent_projects.projects) == MAX_RECENT_PROJS:
recent_projects.projects.pop(-1)
# Reject autosaves.
autosave_dir = utils.get_hidden_user_dir_path() + appconsts.AUTOSAVE_DIR
file_save_dir = os.path.dirname(path) + "/"
if file_save_dir == autosave_dir:
return
try:
index = recent_projects.projects.index(path)
recent_projects.projects.pop(index)
except:
pass
recent_projects.projects.insert(0, path)
save()
def fill_recents_menu_widget(menu_item, callback):
"""
Fills menu item with menuitems to open recent projects.
"""
menu = menu_item.get_submenu()
# Remove current items
items = menu.get_children()
for item in items:
menu.remove(item)
# Add new menu items
recent_proj_names = get_recent_projects()
if len(recent_proj_names) != 0:
for i in range (0, len(recent_proj_names)):
proj_name = recent_proj_names[i]
proj_name = proj_name.replace("_","__") # to display names with underscored correctly
new_item = gtk.MenuItem(proj_name)
new_item.connect("activate", callback, i)
menu.append(new_item)
new_item.show()
# ...or a single non-sensitive Empty item
else:
new_item = gtk.MenuItem(_("Empty"))
new_item.set_sensitive(False)
menu.append(new_item)
new_item.show()
def get_recent_projects():
"""
Returns list of names of recent projects.
"""
proj_list = []
for proj_path in recent_projects.projects:
proj_list.append(os.path.basename(proj_path))
return proj_list
def update_prefs_from_widgets(widgets_tuples_tuple):
# Unpack widgets
gen_opts_widgets, edit_prefs_widgets, view_prefs_widgets = widgets_tuples_tuple
default_profile_combo, open_in_last_opened_check, open_in_last_rendered_check, undo_max_spin, load_order_combo = gen_opts_widgets
auto_play_in_clip_monitor_check, auto_center_check, grfx_insert_length_spin, trim_exit_click, trim_quick_enter, remember_clip_frame = edit_prefs_widgets
disp_splash, buttons_style, dark_theme = view_prefs_widgets
global prefs
prefs.open_in_last_opended_media_dir = open_in_last_opened_check.get_active()
prefs.remember_last_render_dir = open_in_last_rendered_check.get_active()
prefs.default_profile_name = mltprofiles.get_profile_name_for_index(default_profile_combo.get_active())
prefs.undos_max = undo_max_spin.get_adjustment().get_value()
prefs.media_load_order = load_order_combo.get_active()
prefs.auto_play_in_clip_monitor = auto_play_in_clip_monitor_check.get_active()
prefs.auto_center_on_play_stop = auto_center_check.get_active()
prefs.default_grfx_length = int(grfx_insert_length_spin.get_adjustment().get_value())
prefs.empty_click_exits_trims = trim_exit_click.get_active()
prefs.quick_enter_trims = trim_quick_enter.get_active()
prefs.remember_monitor_clip_frame = remember_clip_frame.get_active()
prefs.display_splash_screen = disp_splash.get_active()
prefs.buttons_style = buttons_style.get_active() # styles enum values and widget indexes correspond
prefs.dark_theme = (dark_theme.get_active() == 1)
def get_graphics_default_in_out_length():
in_fr = int(15000/2) - int(prefs.default_grfx_length/2)
out_fr = in_fr + int(prefs.default_grfx_length) - 1 # -1, out inclusive
return (in_fr, out_fr, prefs.default_grfx_length)
def create_thumbs_folder_if_needed(user_dir):
if prefs.thumbnail_folder == None:
thumbs_folder = user_dir + appconsts.THUMBNAILS_DIR
if not os.path.exists(thumbs_folder + "/"):
os.mkdir(thumbs_folder + "/")
prefs.thumbnail_folder = thumbs_folder
def create_rendered_clips_folder_if_needed(user_dir):
if prefs.render_folder == None:
render_folder = user_dir + appconsts.RENDERED_CLIPS_DIR
if not os.path.exists(render_folder + "/"):
os.mkdir(render_folder + "/")
prefs.render_folder = render_folder
class EditorPreferences:
"""
Class holds data of persistant user preferences for editor.
"""
def __init__(self):
self.open_in_last_opended_media_dir = True
self.last_opened_media_dir = None
self.img_length = 2000
self.auto_save_delay_value_index = 1 # value is index of self.AUTO_SAVE_OPTS
self.undos_max = UNDO_STACK_DEFAULT
self.default_profile_name = 10 # index of default profile
self.auto_play_in_clip_monitor = False
self.auto_center_on_play_stop = False
self.thumbnail_folder = None
self.hidden_profile_names = []
self.display_splash_screen = True
self.auto_move_after_edit = False
self.default_grfx_length = 250 # value is in frames
self.track_configuration = 0 # this is index on list appconsts.TRACK_CONFIGURATIONS
self.AUTO_SAVE_OPTS = ((-1, _("No Autosave")),(1, _("1 min")),(2, _("2 min")),(5, _("5 min")))
self.tabs_on_top = False
self.midbar_tc_left = True
self.default_layout = True
self.exit_allocation = (0, 0)
self.media_columns = 2
self.app_v_paned_position = 500 # Paned get/set position value
self.top_paned_position = 600 # Paned get/set position value
self.mm_paned_position = 260 # Paned get/set position value
self.render_folder = None
self.show_sequence_profile = True
self.buttons_style = GLASS_STYLE
self.dark_theme = False
self.remember_last_render_dir = True
self.empty_click_exits_trims = True
self.quick_enter_trims = True
self.show_vu_meter = True
self.remember_monitor_clip_frame = True
self.jack_start_up_op = appconsts.JACK_ON_START_UP_NO
self.jack_frequency = 48000
self.jack_output_type = appconsts.JACK_OUT_AUDIO
self.media_load_order = appconsts.LOAD_ABSOLUTE_FIRST
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module handles creating mlt.Filter objects and their FilterObject python wrappers that
are attached to mlt:Producer objects.
"""
import copy
import pygtk
pygtk.require('2.0');
import gtk
import mlt
import xml.dom.minidom
import appconsts
import editorstate
from editorstate import PROJECT
import mltrefhold
import propertyparse
import respaths
import translations
# Attr and node names in xml describing available filters.
PROPERTY = appconsts.PROPERTY
NON_MLT_PROPERTY = appconsts.NON_MLT_PROPERTY
NAME = appconsts.NAME
ARGS = appconsts.ARGS
MLT_SERVICE = appconsts.MLT_SERVICE
MLT_DROP_VERSION = "mlt_drop_version"
MLT_MIN_VERSION = "mlt_min_version"
EXTRA_EDITOR = appconsts.EXTRA_EDITOR
FILTER = "filter"
GROUP = "group"
ID = "id"
REPLACEMENT_RELATION = "replacementrelation"
USE_SERVICE = "useservice"
DROP_SERVICE = "dropservice"
COMPOSITOR_FILTER_GROUP = "COMPOSITOR_FILTER" # THIS IS NOT USED ANYMORE! DOUBLE CHECK THAT THIS REALLY IS THE CASE AND KILL!
MULTIPART_FILTER = "multipart" # identifies filter as multipart filter
MULTIPART_PROPERTY = "multipartproperty" # Describes properties of multipart filter
MULTIPART_START = "multistartprop" # name of property into which value at start of part-filter is set
MULTIPART_END = "multiendprop" # name of property into which value at start of part-filter is set
# Document
filters_doc = None
# Filters are saved as tuples of group name and array of FilterInfo objects.
groups = []
# Filters that are not present in the system
not_found_filters = []
# dict groupname -> icon
group_icons = None
# Filters that are used as parts of mlttransitions.CompositorObject
# and are not displayed to user
# dict name:FilterInfo
# THIS IS NOT USED ANYMORE! DOUBLE CHECK THAT THIS REALLY IS THE CASE AND KILL!
compositor_filters = {}
# ICONS
FILTER_DEFAULT_ICON = None
# Property types.These map to what mlt accepts.
PROP_INT = appconsts.PROP_INT
PROP_FLOAT = appconsts.PROP_FLOAT
PROP_EXPRESSION = appconsts.PROP_EXPRESSION
# HACK! references to old filters are kept because freeing them causes crashes
old_filters = []
# We need this to mute clips
_volume_filter_info = None
def _load_icons():
global FILTER_DEFAULT_ICON
FILTER_DEFAULT_ICON = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "filter.png")
def _get_group_icon(group_name):
global group_icons
if group_icons == None:
group_icons = {}
group_icons["Color"] = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "color.png")
group_icons["Color Effect"] = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "color_filter.png")
group_icons["Audio"] = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "audio_filter.png")
group_icons["Audio Filter"] = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "audio_filter_sin.png")
group_icons["Blur"] = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "blur_filter.png")
group_icons["Distort"] = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "distort_filter.png")
group_icons["Alpha"] = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "alpha_filter.png")
group_icons["Movement"] = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "movement_filter.png")
group_icons["Transform"] = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "transform.png")
group_icons["Edge"] = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "edge.png")
group_icons["Fix"] = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "fix.png")
group_icons["Artistic"] = FILTER_DEFAULT_ICON
try:
return group_icons[group_name]
except:
return FILTER_DEFAULT_ICON
def _translate_group_name(group_name):
"""
Not implemented.
"""
return translations.filter_groups[group_name]
def get_translated_audio_group_name():
"""
Not implemented.
"""
translations.get_filter_group_name("Audio")
class FilterInfo:
"""
Info of a filter (mlt.Service) that is is available to the user.
Constructor input is a dom node object.
This is used to create FilterObject objects.
"""
def __init__(self, filter_node):
self.mlt_service_id = filter_node.getAttribute(ID)
try:
self.multipart_filter = (filter_node.getAttribute(MULTIPART_FILTER) == "true")
except: # default is False
self.multipart_filter = False
try:
self.mlt_drop_version = filter_node.getAttribute(MLT_DROP_VERSION)
except:
self.mlt_drop_version = None
try:
self.mlt_min_version = filter_node.getAttribute(MLT_MIN_VERSION)
except:
self.mlt_min_version = None
self.xml = filter_node.toxml()
self.name = filter_node.getElementsByTagName(NAME).item(0).firstChild.nodeValue
self.group = filter_node.getElementsByTagName(GROUP).item(0).firstChild.nodeValue
# Properties saved as name-value-type tuplets
p_node_list = filter_node.getElementsByTagName(PROPERTY)
self.properties = propertyparse.node_list_to_properties_array(p_node_list)
# Property args saved in propertyname -> propertyargs_string dict
self.property_args = propertyparse.node_list_to_args_dict(p_node_list)
# Multipart property describes how filters are created and edited when filter
# constists of multiple filters.
# There 0 or 1 of these in the info object.
node_list = filter_node.getElementsByTagName(MULTIPART_PROPERTY)
if len(node_list) == 1:
mp = node_list[0]
value = mp.firstChild.nodeValue
args = mp.getAttribute(ARGS)
start_property = mp.getAttribute(MULTIPART_START)
end_property = mp.getAttribute(MULTIPART_END)
self.multipart_desc = (args, start_property, end_property)
self.multipart_value = value
# Extra editors that handle properties that have been set "no_editor"
e_node_list = filter_node.getElementsByTagName(EXTRA_EDITOR)
self.extra_editors = propertyparse.node_list_to_extraeditors_array(e_node_list)
# Non-MLT properties are persistent values like properties that values are not directly written out as MLT properties
p_node_list = filter_node.getElementsByTagName(NON_MLT_PROPERTY)
self.non_mlt_properties = propertyparse.node_list_to_non_mlt_properties_array(p_node_list)
# Property args for Non-MLT properties saved in propertyname -> propertyargs_string dict
self.property_args.update(propertyparse.node_list_to_args_dict(p_node_list))
def get_icon(self):
return _get_group_icon(self.group)
class FilterObject:
"""
These objects are saved with projects. Thay are used to generate,
update and hold a reference to an mlt.Filter object attached to a mlt.Producer object
representing a clip on the timeline.
These are essentially wrappers to mlt.Filter objects which can't be saved or loaded with pickle().
"""
def __init__(self, filter_info):
self.info = filter_info
# Values of these are edited by the user.
self.properties = copy.deepcopy(filter_info.properties)
try:
self.non_mlt_properties = copy.deepcopy(filter_info.non_mlt_properties)
except:
self.non_mlt_properties = [] # Versions prior 0.14 do not have non_mlt_properties and fail here on load
self.mlt_filter = None # reference to MLT C-object
self.active = True
# PROP_EXPR values may have keywords that need to be replaced with
# numerical values that depend on the profile we have. These need
# to be replaced now that we have profile and we are ready to connect this.
# For example default values of some properties depend on the screen size of the project
propertyparse.replace_value_keywords(self.properties, PROJECT().profile)
def create_mlt_filter(self, mlt_profile):
self.mlt_filter = mlt.Filter(mlt_profile, str(self.info.mlt_service_id))
mltrefhold.hold_ref(self.mlt_filter)
self.update_mlt_filter_properties_all()
def update_mlt_filter_properties_all(self):
"""
Called at creation time and when loaded to set all mlt properties
of a compositor filter to correct values.
"""
for prop in self.properties:
name, value, prop_type = prop
self.mlt_filter.set(str(name), str(value)) # new const strings are created from values
def update_mlt_disabled_value(self):
if self.active == True:
self.mlt_filter.set("disable", str(0))
else:
self.mlt_filter.set("disable", str(1))
def reset_values(self, mlt_profile=None, clip=None): #multipartfilters need profile and clip
for i in range(0, len(self.properties)):
name, o_value, prop_type = self.info.properties[i]
name, value, prop_type = self.properties[i]
self.properties[i] = (name, o_value, prop_type)
self.update_mlt_filter_properties_all()
class MultipartFilterObject:
"""
These objects are saved with projects. Thay are used to generate,
update and hold references to a GROUP of mlt.Filter objects attached to a mlt.Producer object.
"""
def __init__(self, filter_info):
self.info = filter_info
# Values of these are edited by the user.
self.properties = copy.deepcopy(filter_info.properties)
self.non_mlt_properties = copy.deepcopy(filter_info.non_mlt_properties)
self.value = copy.deepcopy(filter_info.multipart_value)
self.active = True
def create_mlt_filters(self, mlt_profile, clip):
self.mlt_filters = []
self.keyframes = self._parse_value_to_keyframes()
# We need always at least 2 keyframes (at the start and end of 1 filter)
# but we only know the position of last keyframe now that we have the clip.
# The default value in filters.xml has only 1 keyframe for frame 0
# so we add the second one now.
if len(self.keyframes) == 1:
f, v = self.keyframes[0]
self.value = self.value.strip('"') + ";" + str(clip.get_length()) + "=" + str(v)
self.keyframes.append((clip.get_length(), v))
self.create_filters_for_keyframes(self.keyframes, mlt_profile)
self.update_mlt_filters_values(self.keyframes)
def update_value(self, kf_str, clip, mlt_profile):
new_kf = self._parse_string_to_keyframes(kf_str)
# If same amount of keyframes, just update values
if len(new_kf) == len(self.keyframes):
self.update_mlt_filters_values(new_kf)
self.keyframes = new_kf
else:
self.detach_all_mlt_filters(clip)
old_filters.append(self.mlt_filters) # hack to prevent object release crashes
self.mlt_filters = []
self.keyframes = new_kf
self.create_filters_for_keyframes(self.keyframes, mlt_profile)
self.update_mlt_filters_values(self.keyframes)
self.attach_all_mlt_filters(clip)
self.value = kf_str
def create_filters_for_keyframes(self, keyframes, mlt_profile):
for i in range(0, len(keyframes) - 1): # Theres one less filter parts than keyframes
mlt_filter = mlt.Filter(mlt_profile, str(self.info.mlt_service_id))
mltrefhold.hold_ref(mlt_filter)
self.mlt_filters.append(mlt_filter)
def update_mlt_filters_values(self, keyframes):
"""
Called obove at creation time and when loaded to set all mlt properties
of all filters
"""
args, start_property, end_property = self.info.multipart_desc
for i in range(0, len(keyframes) - 1):
start_frame, start_value = keyframes[i]
end_frame, end_value = keyframes[i + 1]
mlt_filter = self.mlt_filters[i]
# Set all property values to defaults
for property in self.properties:
name, val, type = property
mlt_filter.set(str(name), str(val))
# set in and out points
mlt_filter.set("in", str(start_frame))
end_frame = int(end_frame) - 1
mlt_filter.set("out", str(end_frame))
# set start and end values
mlt_filter.set(str(start_property), str(start_value)) # Value at start of filter part
mlt_filter.set(str(end_property), str(end_value)) # Value at end of filter part
def _parse_value_to_keyframes(self):
return self._parse_string_to_keyframes(self.value)
def _parse_string_to_keyframes(self, kf_string):
# returs list of (frame, value) tuples
value = kf_string.strip('"') # for some reason we have to use " around values or something broke
parts = value.split(";")
kfs = []
for part in parts:
tokens = part.split("=")
kfs.append((tokens[0],tokens[1]))
return kfs
def attach_all_mlt_filters(self, clip):
for f in self.mlt_filters:
clip.attach(f)
def detach_all_mlt_filters(self, clip):
for f in self.mlt_filters:
clip.detach(f)
def update_mlt_disabled_value(self):
if self.active == True:
for f in self.mlt_filters:
f.set("disable", str(0))
else:
for f in self.mlt_filters:
f.set("disable", str(1))
def reset_values(self, mlt_profile, clip):
self.value = copy.deepcopy(self.info.multipart_value)
self.update_value(self.value, clip, mlt_profile)
def load_filters_xml(services):
"""
Load filters document and save filters nodes as FilterInfo objects in array.
Save them also as array of tuples of names and arrays of FilterInfo objects
that represent named groups of filters as displayd to user.
"""
_load_icons()
print "Loading filters..."
global filters_doc
filters_doc = xml.dom.minidom.parse(respaths.FILTERS_XML_DOC)
load_groups = {}
filter_nodes = filters_doc.getElementsByTagName(FILTER)
for f_node in filter_nodes:
filter_info = FilterInfo(f_node)
if filter_info.mlt_drop_version != "":
if editorstate.mlt_version_is_equal_or_greater(filter_info.mlt_drop_version):
print filter_info.name + " dropped, MLT version too high for this filter."
continue
if filter_info.mlt_min_version != "":
if not editorstate.mlt_version_is_equal_or_greater(filter_info.mlt_min_version):
print filter_info.name + " dropped, MLT version too low for this filter."
continue
if (not filter_info.mlt_service_id in services) and len(services) > 0:
print "MLT service " + filter_info.mlt_service_id + " not found."
global not_found_filters
not_found_filters.append(filter_info)
continue
if filter_info.mlt_service_id == "volume": # we need this filter to do mutes so save reference to it
global _volume_filter_info
_volume_filter_info = filter_info
# Add filter compositor filters or filter groups
if filter_info.group == COMPOSITOR_FILTER_GROUP:
global compositor_filters
compositor_filters[filter_info.name] = filter_info
else:
translated_group_name = _translate_group_name(filter_info.group)
try:
group = load_groups[translated_group_name]
group.append(filter_info)
except:
load_groups[translated_group_name] = [filter_info]
# We used translated group names as keys in load_groups
# Now we sort them and use them to place data in groups array in the same
# order as it will be presented to user, so selection indexes in gui components will match
# group array indexes here.
sorted_keys = sorted(load_groups.keys())
global groups
for gkey in sorted_keys:
group = load_groups[gkey]
add_group = sorted(group, key=lambda finfo: translations.get_filter_name(finfo.name) )
groups.append((gkey, add_group))
def clone_filter_object(filter_object, mlt_profile):
"""
Creates new filter object with with copied properties values.
"""
clone = FilterObject(filter_object.info)
clone.properties = copy.deepcopy(filter_object.properties)
clone.create_mlt_filter(mlt_profile)
return clone
def replace_services(services):
# this has gotta be a bullshit way to do this
replacements_doc = xml.dom.minidom.parse(respaths.REPLACEMENTS_XML_DOC)
# Build dict that has enough info to enable deleting and finding filters by name
filters_dict = {}
for group_data in groups:
gkey, group = group_data
for f in group:
filters_dict[f.name] = (f, group)
# Replace services
replacement_nodes = replacements_doc.getElementsByTagName(REPLACEMENT_RELATION)
for r_node in replacement_nodes:
# Get use service values
use_node = r_node.getElementsByTagName(USE_SERVICE).item(0)
use_service_id = use_node.getAttribute(ID)
use_service_name = use_node.getAttribute(NAME)
# Try replace if use service and use filter exist
if (use_service_id in services) and len(services) > 0:
try:
use_service_data = filters_dict[use_service_name]
except:
print "Replace service " + use_service_name + " not found."
continue
drop_nodes = r_node.getElementsByTagName(DROP_SERVICE)
try:
# Drop service if found
for d_node in drop_nodes:
drop_service_id = d_node.getAttribute(ID)
drop_service_name = d_node.getAttribute(NAME)
drop_service_data = filters_dict[drop_service_name]
f_info, group = drop_service_data
for i in range(0, len(group)):
if group[i].name == f_info.name:
group.pop(i)
print f_info.name +" dropped for " + use_service_name
break
except:
print "Dropping a mlt service for " + use_service_name + " failed, maybe not present."
def get_compositor_filter(filter_id):
return compositor_filters[filter_id]
def get_audio_filters_groups():
for group_tuple in groups:
gkey, group = group_tuple
if gkey == translations.get_filter_group_name("Audio"):
group_tuple1 = group_tuple
if gkey == translations.get_filter_group_name("Audio Filter"):
group_tuple2 = group_tuple
return [group_tuple1, group_tuple2]
def get_volume_filters_info():
return _volume_filter_info
def detach_all_filters(clip):
for f in clip.filters:
if isinstance(f, FilterObject):
clip.detach(f.mlt_filter)
else:# f is mltfilters.MultiFilterObject
f.detach_all_mlt_filters(clip)
def attach_all_filters(clip):
for f in clip.filters:
if isinstance(f, FilterObject):
clip.attach(f.mlt_filter)
else:# f is mltfilters.MultiFilterObject
f.attach_all_mlt_filters(clip)
def get_all_found_filters():
all_filters = []
for group_tuple in groups:
gkey, group = group_tuple
all_filters = all_filters + group
return all_filters
def print_found_filters():
all_filters = get_all_found_filters()
for f in all_filters:
print f.mlt_service_id + " for filter " + f.name + " available"
def print_not_found_filters():
for f in not_found_filters:
print f.mlt_service_id + " for filter " + f.name + " not found"
# ------------------------------------------------------------- mute filters
def create_mute_volume_filter(seq):
mute_filter = seq.create_filter(get_volume_filters_info())
mute_filter.mlt_filter.set("gain","0")
mute_filter.mlt_filter.set("end","0")
return mute_filter
def do_clip_mute(clip, volume_filter):
clip.attach(volume_filter.mlt_filter)
clip.mute_filter = volume_filter
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2014 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
import appconsts
"""
Module for data objects used my multiple modules.
"""
class ProjectProxyEditingData:
def __init__(self):
self.proxy_mode = appconsts.USE_ORIGINAL_MEDIA
self.create_rules = None # not impl.
self.encoding = 0 # default is first found encoding
self.size = 1 # default is half project size
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Application module.
Handles application initialization, shutdown, opening projects, autosave and changing
sequences.
"""
import gobject
import pygtk
pygtk.require('2.0');
import glib
import gtk
import locale
import md5
import mlt
import os
import sys
import time
import appconsts
import audiomonitoring
import audiowaveform
import clipeffectseditor
import clipmenuaction
import compositeeditor
import dialogs
import dialogutils
import dnd
import edit
import editevent
import editorpersistance
import editorstate
import editorwindow
import gui
import keyevents
import medialog
import mlt
import mltenv
import mltfilters
import mltplayer
import mltprofiles
import mlttransitions
import movemodes
import persistance
import preferenceswindow
import projectaction
import projectdata
import projectinfogui
import proxyediting
import render
import renderconsumer
import respaths
import resync
import sequence
import tlinewidgets
import translations
import undo
import updater
import utils
import jackaudio
AUTOSAVE_DIR = appconsts.AUTOSAVE_DIR
AUTOSAVE_FILE = "autosave/autosave"
instance_autosave_id_str = None
PID_FILE = "flowbladepidfile"
BATCH_DIR = "batchrender/"
autosave_timeout_id = -1
recovery_dialog_id = -1
loaded_autosave_file = None
splash_screen = None
splash_timeout_id = -1
exit_timeout_id = -1
logger = None
def main(root_path):
"""
Called at application start.
Initializes application with a default project.
"""
# Print OS, Python version and GTK+ version
try:
os_release_file = open("/etc/os-release","r")
os_text = os_release_file.read()
s_index = os_text.find("PRETTY_NAME=")
e_index = os_text.find("\n", s_index)
print "OS: " + os_text[s_index + 13:e_index - 1]
except:
pass
print "Python", sys.version
print "GTK+ version:", gtk.gtk_version
editorstate.gtk_version = gtk.gtk_version
try:
editorstate.mlt_version = mlt.LIBMLT_VERSION
except:
editorstate.mlt_version = "0.0.99" # magic string for "not found"
# Create hidden folders if not present
user_dir = utils.get_hidden_user_dir_path()
if not os.path.exists(user_dir):
os.mkdir(user_dir)
if not os.path.exists(user_dir + mltprofiles.USER_PROFILES_DIR):
os.mkdir(user_dir + mltprofiles.USER_PROFILES_DIR)
if not os.path.exists(user_dir + AUTOSAVE_DIR):
os.mkdir(user_dir + AUTOSAVE_DIR)
if not os.path.exists(user_dir + BATCH_DIR):
os.mkdir(user_dir + BATCH_DIR)
if not os.path.exists(user_dir + appconsts.AUDIO_LEVELS_DIR):
os.mkdir(user_dir + appconsts.AUDIO_LEVELS_DIR)
if not os.path.exists(utils.get_hidden_screenshot_dir_path()):
os.mkdir(utils.get_hidden_screenshot_dir_path())
# Set paths.
respaths.set_paths(root_path)
# Init translations module with translations data
translations.init_languages()
translations.load_filters_translations()
mlttransitions.init_module()
# Load editor prefs and list of recent projects
editorpersistance.load()
if editorpersistance.prefs.dark_theme == True:
respaths.apply_dark_theme()
editorpersistance.create_thumbs_folder_if_needed(user_dir)
editorpersistance.create_rendered_clips_folder_if_needed(user_dir)
editorpersistance.save()
# Init gtk threads
gtk.gdk.threads_init()
gtk.gdk.threads_enter()
# Load drag'n'drop images
dnd.init()
# Adjust gui parameters for smaller screens
scr_w = gtk.gdk.screen_width()
scr_h = gtk.gdk.screen_height()
editorstate.SCREEN_WIDTH = scr_w
editorstate.SCREEN_HEIGHT = scr_h
_set_draw_params(scr_w, scr_h)
# Refuse to run on too small screen.
if scr_w < 1151 or scr_h < 767:
_too_small_screen_exit()
return
# Splash screen
if editorpersistance.prefs.display_splash_screen == True:
show_splash_screen()
# Init MLT framework
repo = mlt.Factory().init()
# Set numeric locale to use "." as radix, MLT initilizes this to OS locale and this causes bugs
locale.setlocale(locale.LC_NUMERIC, 'C')
# Check for codecs and formats on the system
mltenv.check_available_features(repo)
renderconsumer.load_render_profiles()
# Load filter and compositor descriptions from xml files.
mltfilters.load_filters_xml(mltenv.services)
mlttransitions.load_compositors_xml(mltenv.transitions)
# Replace some services if better replacements available
mltfilters.replace_services(mltenv.services)
# Create list of available mlt profiles
mltprofiles.load_profile_list()
# Launch association file if found in arguments
launch_file_path = get_assoc_file_path()
if launch_file_path != None:
try:
print "Launching assoc file:" + launch_file_path
persistance.show_messages = False
editorstate.project = persistance.load_project(launch_file_path)
persistance.show_messages = True
check_crash = False
except:
editorstate.project = projectdata.get_default_project()
persistance.show_messages = True
check_crash = True
else:
# There is always a project open, so at startup we create a default project.
# Set default project as the project being edited.
editorstate.project = projectdata.get_default_project()
check_crash = True
# Audiomonitoring being available needs to be known before GUI creation
audiomonitoring.init(editorstate.project.profile)
# Create player object
create_player()
# Create main window and set widget handles in gui.py for more convenient reference.
create_gui()
# Inits widgets with project data
init_project_gui()
# Inits widgets with current sequence data
init_sequence_gui()
# Launch player now that data and gui exist
launch_player()
# Editor and modules need some more initializing
init_editor_state()
# Tracks need to be recentered if window is resized.
# Connect listener for this now that the tline panel size allocation is sure to be available.
gui.editor_window.window.connect("size-allocate", lambda w, e:updater.window_resized())
gui.editor_window.window.connect("window-state-event", lambda w, e:updater.window_resized())
# Get existing autosave files
autosave_files = get_autosave_files()
# Show splash
if ((editorpersistance.prefs.display_splash_screen == True) and len(autosave_files) == 0):
global splash_timeout_id
splash_timeout_id = gobject.timeout_add(2600, destroy_splash_screen)
splash_screen.show_all()
appconsts.SAVEFILE_VERSION = projectdata.SAVEFILE_VERSION # THIS IS A QUESTIONABLE IDEA TO SIMPLIFY IMPORTS, NOT DRY. WHEN DOING TOOLS THAT RUN IN ANOTHER PROCESSES AND SAVE PROJECTS, THIS LINE NEEDS TO BE THERE ALSO.
# Every running instance has unique autosave file which is deleted at exit
set_instance_autosave_id()
# Existance of autosave file hints that program was exited abnormally
if check_crash == True and len(autosave_files) > 0:
if len(autosave_files) == 1:
gobject.timeout_add(10, autosave_recovery_dialog)
else:
gobject.timeout_add(10, autosaves_many_recovery_dialog)
else:
start_autosave()
# We prefer to monkeypatch some callbacks into some modules, usually to
# maintain a simpler and non-circular import structure
monkeypatch_callbacks()
# Launch gtk+ main loop
gtk.main()
gtk.gdk.threads_leave()
# ----------------------------------- callback setting
def monkeypatch_callbacks():
# Prefences setting
preferenceswindow.select_thumbnail_dir_callback = projectaction.select_thumbnail_dir_callback
preferenceswindow.select_render_clips_dir_callback = projectaction.select_render_clips_dir_callback
# We need to do this on app start-up or
# we'll get circular imports with projectaction->mltplayer->render->projectaction
render.open_media_file_callback = projectaction.open_rendered_file
# Set callback for undo/redo ops, batcherrender app does not need this
undo.set_post_undo_redo_callback(editevent.set_post_undo_redo_edit_mode)
undo.repaint_tline = updater.repaint_tline
# # Drag'n'drop callbacks
dnd.add_current_effect = clipeffectseditor.add_currently_selected_effect
dnd.display_monitor_media_file = updater.set_and_display_monitor_media_file
dnd.range_log_items_tline_drop = editevent.tline_range_item_drop
dnd.range_log_items_log_drop = medialog.clips_drop
# Media log
medialog.do_multiple_clip_insert_func = editevent.do_multiple_clip_insert
editevent.display_clip_menu_pop_up = clipmenuaction.display_clip_menu
editevent.compositor_menu_item_activated = clipmenuaction._compositor_menu_item_activated
# These provide clues for further module refactoring
# ---------------------------------- program, sequence and project init
def get_assoc_file_path():
"""
Check if were opening app with file association launch from Gnome
"""
arg_str = ""
for arg in sys.argv:
arg_str = arg
if len(arg_str) == 0:
return None
ext_index = arg_str.find(".flb")
if ext_index == -1:
return None
else:
return arg_str
def create_gui():
"""
Called at app start to create gui objects and handles for them.
"""
tlinewidgets.load_icons()
updater.set_clip_edit_mode_callback = editevent.set_clip_monitor_edit_mode
updater.load_icons()
# Create window and all child components
editor_window = editorwindow.EditorWindow()
# Make references to various gui components available via gui module
gui.capture_references(editor_window)
# Connect window global key listener
gui.editor_window.window.connect("key-press-event", keyevents.key_down)
# Give undo a reference to uimanager for menuitem state changes
undo.set_menu_items(gui.editor_window.uimanager)
# Set button to display sequence in toggled state.
gui.sequence_editor_b.set_active(True)
def create_player():
"""
Creates mlt player object
"""
# Create player and make available from editorstate module.
editorstate.player = mltplayer.Player(editorstate.project.profile)
editorstate.player.set_tracktor_producer(editorstate.current_sequence().tractor)
def launch_player():
# Create SDL output consumer
editorstate.player.set_sdl_xwindow(gui.tline_display)
editorstate.player.create_sdl_consumer()
# Display current sequence tractor
updater.display_sequence_in_monitor()
# Connect buttons to player methods
gui.editor_window.connect_player(editorstate.player)
# Start player.
editorstate.player.connect_and_start()
def init_project_gui():
"""
Called after project load to initialize interface
"""
# Display media files in "Media" tab
gui.media_list_view.fill_data_model()
try: # Fails if current bin is empty
selection = gui.media_list_view.treeview.get_selection()
selection.select_path("0")
except Exception:
pass
# Display bins in "Media" tab
gui.bin_list_view.fill_data_model()
selection = gui.bin_list_view.treeview.get_selection()
selection.select_path("0")
# Display sequences in "Project" tab
gui.sequence_list_view.fill_data_model()
selection = gui.sequence_list_view.treeview.get_selection()
selected_index = editorstate.project.sequences.index(editorstate.current_sequence())
selection.select_path(str(selected_index))
# Display logged ranges in "Range Log" tab
medialog.update_media_log_view()
render.set_default_values_for_widgets(True)
gui.tline_left_corner.update_gui()
projectinfogui.update_project_info()
# Set render folder selector to last render if prefs require
folder_path = editorstate.PROJECT().get_last_render_folder()
if folder_path != None and editorpersistance.prefs.remember_last_render_dir == True:
gui.render_out_folder.set_current_folder(folder_path)
def init_sequence_gui():
"""
Called after project load or changing current sequence
to initialize interface.
"""
# Set initial timeline scale draw params
editorstate.current_sequence().update_length()
updater.update_pix_per_frame_full_view()
updater.init_tline_scale()
updater.repaint_tline()
def init_editor_state():
"""
Called after project load or changing current sequence
to initalize editor state.
"""
render.fill_out_profile_widgets()
gui.media_view_filter_selector.set_pixbuf(editorstate.media_view_filter)
gui.clip_editor_b.set_sensitive(False)
gui.editor_window.window.set_title(editorstate.project.name + " - Flowblade")
gui.editor_window.uimanager.get_widget("/MenuBar/FileMenu/Save").set_sensitive(False)
gui.editor_window.uimanager.get_widget("/MenuBar/EditMenu/Undo").set_sensitive(False)
gui.editor_window.uimanager.get_widget("/MenuBar/EditMenu/Redo").set_sensitive(False)
# Center tracks vertical display and init some listeners to
# new value and repaint tracks column.
tlinewidgets.set_ref_line_y(gui.tline_canvas.widget.allocation)
gui.tline_column.init_listeners()
gui.tline_column.widget.queue_draw()
# Clear editors
clipeffectseditor.clear_clip()
compositeeditor.clear_compositor()
# Show first pages on notebooks
gui.middle_notebook.set_current_page(0)
# Clear clip selection.
movemodes.clear_selection_values()
# Set initial edit mode
gui.editor_window.modes_selector.set_pixbuf(0)
editevent.insert_move_mode_pressed()
# Create array needed to update compositors after all edits
editorstate.current_sequence().restack_compositors()
proxyediting.set_menu_to_proxy_state()
# Enable edit action GUI updates
edit.do_gui_update = True
def new_project(profile_index, v_tracks, a_tracks):
sequence.VIDEO_TRACKS_COUNT = v_tracks
sequence.AUDIO_TRACKS_COUNT = a_tracks
profile = mltprofiles.get_profile_for_index(profile_index)
new_project = projectdata.Project(profile)
open_project(new_project)
def open_project(new_project):
stop_autosave()
audiomonitoring.close_audio_monitor()
editorstate.project = new_project
editorstate.media_view_filter = appconsts.SHOW_ALL_FILES
# Inits widgets with project data
init_project_gui()
# Inits widgets with current sequence data
init_sequence_gui()
# Set and display current sequence tractor
display_current_sequence()
# Editor and modules need some more initializing
init_editor_state()
# For save time message on close
projectaction.save_time = None
# Delete autosave file after it has been loaded
global loaded_autosave_file
if loaded_autosave_file != None:
print "Deleting", loaded_autosave_file
os.remove(loaded_autosave_file)
loaded_autosave_file = None
editorstate.update_current_proxy_paths()
audiomonitoring.init_for_project_load()
updater.window_resized()
start_autosave()
def change_current_sequence(index):
stop_autosave()
editorstate.project.c_seq = editorstate.project.sequences[index]
# Inits widgets with current sequence data
init_sequence_gui()
# update resync data
resync.sequence_changed(editorstate.project.c_seq)
# Set and display current sequence tractor
display_current_sequence()
# Editor and modules needs to do some initializing
init_editor_state()
# Display current sequence selected in gui.
gui.sequence_list_view.fill_data_model()
selection = gui.sequence_list_view.treeview.get_selection()
selected_index = editorstate.project.sequences.index(editorstate.current_sequence())
selection.select_path(str(selected_index))
start_autosave()
def display_current_sequence():
# Get shorter alias.
player = editorstate.player
player.consumer.stop()
player.init_for_profile(editorstate.project.profile)
player.create_sdl_consumer()
player.set_tracktor_producer(editorstate.current_sequence().tractor)
player.connect_and_start()
updater.display_sequence_in_monitor()
player.seek_frame(0)
updater.repaint_tline()
# ------------------------------------------------- autosave
def autosave_recovery_dialog():
dialogs.autosave_recovery_dialog(autosave_dialog_callback, gui.editor_window.window)
return False
def autosave_dialog_callback(dialog, response):
dialog.destroy()
autosave_file = utils.get_hidden_user_dir_path() + AUTOSAVE_DIR + get_autosave_files()[0]
if response == gtk.RESPONSE_OK:
global loaded_autosave_file
loaded_autosave_file = autosave_file
projectaction.actually_load_project(autosave_file, True)
else:
os.remove(autosave_file)
start_autosave()
def autosaves_many_recovery_dialog():
autosaves_file_names = get_autosave_files()
now = time.time()
autosaves = []
for a_file_name in autosaves_file_names:
autosave_path = utils.get_hidden_user_dir_path() + AUTOSAVE_DIR + a_file_name
autosave_object = utils.EmptyClass()
autosave_object.age = now - os.stat(autosave_path).st_mtime
autosave_object.path = autosave_path
autosaves.append(autosave_object)
autosaves = sorted(autosaves, key=lambda autosave_object: autosave_object.age)
dialogs.autosaves_many_recovery_dialog(autosaves_many_dialog_callback, autosaves, gui.editor_window.window)
return False
def autosaves_many_dialog_callback(dialog, response, autosaves_view, autosaves):
if response == gtk.RESPONSE_OK:
autosave_file = autosaves[autosaves_view.get_selected_indexes_list()[0]].path # Single selection, 1 quaranteed to exist
print "autosave_file", autosave_file
global loaded_autosave_file
loaded_autosave_file = autosave_file
dialog.destroy()
projectaction.actually_load_project(autosave_file, True)
else:
dialog.destroy()
start_autosave()
def set_instance_autosave_id():
global instance_autosave_id_str
instance_autosave_id_str = "_" + md5.new(str(os.urandom(32))).hexdigest()
def get_instance_autosave_file():
return AUTOSAVE_FILE + instance_autosave_id_str
def start_autosave():
global autosave_timeout_id
time_min = 1 # hard coded, probably no need to make configurable
autosave_delay_millis = time_min * 60 * 1000
print "Autosave started..."
autosave_timeout_id = gobject.timeout_add(autosave_delay_millis, do_autosave)
autosave_file = utils.get_hidden_user_dir_path() + get_instance_autosave_file()
persistance.save_project(editorstate.PROJECT(), autosave_file)
def get_autosave_files():
autosave_dir = utils.get_hidden_user_dir_path() + AUTOSAVE_DIR
return os.listdir(autosave_dir)
def stop_autosave():
global autosave_timeout_id
if autosave_timeout_id == -1:
return
gobject.source_remove(autosave_timeout_id)
autosave_timeout_id = -1
def do_autosave():
autosave_file = utils.get_hidden_user_dir_path() + get_instance_autosave_file()
persistance.save_project(editorstate.PROJECT(), autosave_file)
return True
# ------------------------------------------------- splash screen
def show_splash_screen():
global splash_screen
splash_screen = gtk.Window(gtk.WINDOW_TOPLEVEL)
splash_screen.set_border_width(0)
splash_screen.set_decorated(False)
splash_screen.set_position(gtk.WIN_POS_CENTER)
img = gtk.image_new_from_file(respaths.IMAGE_PATH + "flowblade_splash_black_small.png")
splash_screen.add(img)
splash_screen.set_keep_above(True)
splash_screen.set_size_request(498, 320) # Splash screen is working funny since Ubuntu 13.10
splash_screen.set_resizable(False)
while(gtk.events_pending()):
gtk.main_iteration()
def destroy_splash_screen():
splash_screen.destroy()
gobject.source_remove(splash_timeout_id)
# ------------------------------------------------------- small screens
def _set_draw_params(scr_w, scr_h):
if scr_w < 1220:
appconsts.NOTEBOOK_WIDTH = 580
editorwindow.MONITOR_AREA_WIDTH = 500
if scr_h < 960:
appconsts.TOP_ROW_HEIGHT = 460
if scr_h < 863:
appconsts.TOP_ROW_HEIGHT = 420
sequence.TRACK_HEIGHT_SMALL = appconsts.TRACK_HEIGHT_SMALLEST
tlinewidgets.HEIGHT = 184
tlinewidgets.TEXT_Y_SMALL = 15
tlinewidgets.ID_PAD_Y_SMALL = 2
tlinewidgets.COMPOSITOR_HEIGHT_OFF = 7
tlinewidgets.COMPOSITOR_HEIGHT = 14
tlinewidgets.COMPOSITOR_TEXT_Y = 11
tlinewidgets.INSRT_ICON_POS_SMALL = (81, 4)
def _too_small_screen_exit():
global exit_timeout_id
exit_timeout_id = gobject.timeout_add(200, _show_too_small_info)
# Launch gtk+ main loop
gtk.main()
def _show_too_small_info():
gobject.source_remove(exit_timeout_id)
primary_txt = _("Too small screen for this application.")
scr_w = gtk.gdk.screen_width()
scr_h = gtk.gdk.screen_height()
secondary_txt = _("Minimum screen dimensions for this application are 1152 x 768.\n") + \
_("Your screen dimensions are ") + str(scr_w) + " x " + str(scr_h) + "."
dialogutils.warning_message_with_callback(primary_txt, secondary_txt, None, False, _early_exit)
def _early_exit(dialog, response):
dialog.destroy()
# Exit gtk main loop.
gtk.main_quit()
# ------------------------------------------------------- single instance
def _not_first_instance_exit():
global exit_timeout_id
exit_timeout_id = gobject.timeout_add(200, _show_single_instance_info)
# Launch gtk+ main loop
gtk.main()
def _show_single_instance_info():
gobject.source_remove(exit_timeout_id)
primary_txt = _("Another instance of Flowblade already running.")
secondary_txt = _("Only one instance of Flowblade is allowed to run at a time.")
dialogutils.warning_message_with_callback(primary_txt, secondary_txt, None, False, _early_exit)
# ------------------------------------------------------- logging
def init_logger():
try:
import logging
global logger
logger = logging.getLogger('flowblade')
hdlr = logging.FileHandler('/home/janne/flog')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
except:
print "logging failed"
def log_msg(msg):
global logger
logger.info(msg)
# ------------------------------------------------------ shutdown
def shutdown():
dialogs.exit_confirm_dialog(_shutdown_dialog_callback, get_save_time_msg(), gui.editor_window.window, editorstate.PROJECT().name)
return True # Signal that event is handled, otherwise it'll destroy window anyway
def get_save_time_msg():
if projectaction.save_time == None:
return _("Project has not been saved since it was opened.")
save_ago = (time.clock() - projectaction.save_time) / 60.0
if save_ago < 1:
return _("Project was saved less than a minute ago.")
if save_ago < 2:
return _("Project was saved one minute ago.")
return _("Project was saved ") + str(int(save_ago)) + _(" minutes ago.")
def _shutdown_dialog_callback(dialog, response_id):
dialog.destroy()
if response_id == gtk.RESPONSE_CLOSE:# "Don't Save"
pass
elif response_id == gtk.RESPONSE_YES:# "Save"
if editorstate.PROJECT().last_save_path != None:
persistance.save_project(editorstate.PROJECT(), editorstate.PROJECT().last_save_path)
else:
dialogutils.warning_message(_("Project has not been saved previously"),
_("Save project with File -> Save As before closing."),
gui.editor_window.window)
return
else: # "Cancel"
return
# --- APP SHUT DOWN --- #
print "Exiting app..."
# No more auto saving
stop_autosave()
# Save window dimensions on exit
x, y, w, h = gui.editor_window.window.get_allocation()
editorpersistance.prefs.exit_allocation = (w, h)
editorpersistance.prefs.app_v_paned_position = gui.editor_window.app_v_paned.get_position()
editorpersistance.prefs.top_paned_position = gui.editor_window.top_paned.get_position()
editorpersistance.prefs.mm_paned_position = gui.editor_window.mm_paned.get_position()
editorpersistance.save()
# Block reconnecting consumer before setting window not visible
updater.player_refresh_enabled = False
gui.editor_window.window.set_visible(False)
# Close and destroy app when gtk finds time to do it after hiding window
glib.idle_add(_app_destroy)
def _app_destroy():
# Close threads and stop mlt consumers
editorstate.player.shutdown() # has ticker thread and player threads running
audiomonitoring.close()
# Wait threads to stop
while((editorstate.player.ticker.exited == False) and
(audiomonitoring._update_ticker.exited == False) and
(audiowaveform.waveform_thread != None)):
pass
# Delete autosave file
try:
os.remove(utils.get_hidden_user_dir_path() + get_instance_autosave_file())
except:
print "Delete autosave file FAILED"
# Exit gtk main loop.
gtk.main_quit()
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Modules handles creating and caching audio waveform images for clips.
"""
import pygtk
pygtk.require('2.0');
import gtk
import math
import md5
import mlt
import os
import pickle
import struct
import threading
import time
import appconsts
import dialogutils
from editorstate import PROJECT
import gui
import guiutils
import updater
import utils
# Frame level value cache for audio levels
# path -> list of frame levels
frames_cache = {}
waveform_thread = None
LEFT_CHANNEL = "_audio_level.0"
RIGHT_CHANNEL = "_audio_level.1"
# ------------------------------------------------- waveforms
def set_waveform_displayer_clip_from_popup(data):
clip, track, item_id, item_data = data
global frames_cache
if clip.path in frames_cache:
frame_levels = frames_cache[clip.path]
clip.waveform_data = frame_levels
return
cache_file_path = utils.get_hidden_user_dir_path() + appconsts.AUDIO_LEVELS_DIR + _get_unique_name_for_media(clip.path)
if os.path.isfile(cache_file_path):
f = open(cache_file_path)
frame_levels = pickle.load(f)
frames_cache[clip.path] = frame_levels
clip.waveform_data = frame_levels
return
progress_bar = gtk.ProgressBar()
title = _("Audio Levels Data Render")
text = "<b>Media File: </b>" + clip.path
dialog = _waveform_render_progress_dialog(_waveform_render_abort, title, text, progress_bar, gui.editor_window.window)
dialog.progress_bar = progress_bar
global waveform_thread
waveform_thread = WaveformCreator(clip, track.height, dialog)
waveform_thread.start()
def _waveform_render_abort(dialog, response_id):
if waveform_thread != None:
waveform_thread.abort_rendering()
def _waveform_render_stop(dialog, response_id):
global waveform_thread
waveform_thread = None
dialogutils.delay_destroy_window(dialog, 1.6)
def clear_waveform(data):
# LOOK TO REMOVE; DOES NOT SEEMS CURRENT
clip, track, item_id, item_data = data
clip.waveform_data = None
clip.waveform_data_frame_height = -1
updater.repaint_tline()
def _get_unique_name_for_media(media_file_path):
size_str = str(os.path.getsize(media_file_path))
file_name = md5.new(media_file_path + size_str).hexdigest()
return file_name
class WaveformCreator(threading.Thread):
def __init__(self, clip, track_height, dialog):
threading.Thread.__init__(self)
self.clip = clip
self.temp_clip = self._get_temp_producer(clip)
self.file_cache_path = utils.get_hidden_user_dir_path() + appconsts.AUDIO_LEVELS_DIR + _get_unique_name_for_media(clip.path)
self.track_height = track_height
self.abort = False
self.clip_media_length = PROJECT().get_media_file_for_path(self.clip.path).length
self.last_rendered_frame = 0
self.stopped = False
self.dialog = dialog
def run(self):
global frames_cache
frame_levels = [None] * self.clip_media_length
frames_cache[self.clip.path] = frame_levels
gtk.gdk.threads_enter()
self.dialog.progress_bar.set_fraction(0.0)
self.dialog.progress_bar.set_text(str(0) + "%")
while(gtk.events_pending()):
gtk.main_iteration()
gtk.gdk.threads_leave()
time.sleep(0.2)
for frame in range(0, len(frame_levels)):
if self.abort:
break
self.temp_clip.seek(frame)
mlt.frame_get_waveform(self.temp_clip.get_frame(), 10, 50)
val = self.levels.get(RIGHT_CHANNEL)
if val == None:
val = 0.0
frame_levels[frame] = float(val)
self.last_rendered_frame = frame
if frame % 500 == 0:
render_fraction = float(self.last_rendered_frame) / float(self.clip_media_length)
gtk.gdk.threads_enter()
self.dialog.progress_bar.set_fraction(render_fraction)
pros = int(render_fraction * 100)
self.dialog.progress_bar.set_text(str(pros) + "%")
while(gtk.events_pending()):
gtk.main_iteration()
gtk.gdk.threads_leave()
time.sleep(0.1)
if not self.abort:
self.clip.waveform_data = frame_levels
write_file = file(self.file_cache_path, "wb")
pickle.dump(frame_levels, write_file)
gtk.gdk.threads_enter()
self.dialog.progress_bar.set_fraction(1.0)
self.dialog.progress_bar.set_text(_("Saving to Hard Drive"))
gtk.gdk.threads_leave()
else:
frames_cache.pop(self.clip.path, None)
updater.repaint_tline()
# Set thread ref to None to flag that no waveforms are being created
global waveform_thread
waveform_thread = None
_waveform_render_stop(self.dialog, None)
def _get_temp_producer(self, clip):
service = clip.get("mlt_service")
if service.startswith("xml"):
service = "xml-nogl"
temp_producer = mlt.Producer(PROJECT().profile, service.encode('utf-8'), clip.get("resource"))
channels = mlt.Filter(PROJECT().profile, "audiochannels")
converter = mlt.Filter(PROJECT().profile, "audioconvert")
self.levels = mlt.Filter(PROJECT().profile, "audiolevel")
temp_producer.attach(channels)
temp_producer.attach(converter)
temp_producer.attach(self.levels)
temp_producer.path = clip.path
return temp_producer
def abort_rendering(self):
self.abort = True
def _waveform_render_progress_dialog(callback, title, text, progress_bar, parent_window):
dialog = gtk.Dialog(title,
parent_window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(_("Cancel").encode('utf-8'), gtk.RESPONSE_REJECT))
dialog.text_label = gtk.Label(text)
dialog.text_label.set_use_markup(True)
text_box = gtk.HBox(False, 2)
text_box.pack_start(dialog.text_label,False, False, 0)
text_box.pack_start(gtk.Label(), True, True, 0)
status_box = gtk.HBox(False, 2)
status_box.pack_start(text_box, False, False, 0)
status_box.pack_start(gtk.Label(), True, True, 0)
progress_vbox = gtk.VBox(False, 2)
progress_vbox.pack_start(status_box, False, False, 0)
progress_vbox.pack_start(guiutils.get_pad_label(10, 10), False, False, 0)
progress_vbox.pack_start(progress_bar, False, False, 0)
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(12, 12, 12, 12)
alignment.add(progress_vbox)
dialog.vbox.pack_start(alignment, True, True, 0)
dialog.set_default_size(500, 125)
alignment.show_all()
dialog.set_has_separator(False)
dialog.connect('response', callback)
dialog.show()
return dialog
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2013 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
import pygtk
pygtk.require('2.0');
import gtk
import os
import dialogutils
import gui
import guiutils
from editorstate import current_sequence
import mltprofiles
import renderconsumer
import respaths
import utils
destroy_window_event_id = -1
FFMPEG_VIEW_SIZE = (200, 210) # Text edit area height for render opts. Width 200 seems to be ignored in current layout?
# ----------------------------------------------------------- dialogs
def render_progress_dialog(callback, parent_window, frame_rates_match=True):
dialog = gtk.Dialog(_("Render Progress"),
parent_window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(_("Cancel").encode('utf-8'), gtk.RESPONSE_REJECT))
dialog.status_label = gtk.Label()
dialog.remaining_time_label = gtk.Label()
dialog.passed_time_label = gtk.Label()
dialog.progress_bar = gtk.ProgressBar()
status_box = gtk.HBox(False, 2)
status_box.pack_start(dialog.status_label,False, False, 0)
status_box.pack_start(gtk.Label(), True, True, 0)
remaining_box = gtk.HBox(False, 2)
remaining_box.pack_start(dialog.remaining_time_label,False, False, 0)
remaining_box.pack_start(gtk.Label(), True, True, 0)
passed_box = gtk.HBox(False, 2)
passed_box.pack_start(dialog.passed_time_label,False, False, 0)
passed_box.pack_start(gtk.Label(), True, True, 0)
if frame_rates_match == False:
warning_icon = gtk.image_new_from_stock(gtk.STOCK_DIALOG_WARNING, gtk.ICON_SIZE_MENU)
warning_text = gtk.Label(_("Project and Render Profile FPS values are not same. Rendered file may have A/V sync issues."))
warning_box = gtk.HBox(False, 2)
warning_box.pack_start(warning_icon,False, False, 0)
warning_box.pack_start(warning_text,False, False, 0)
warning_box.pack_start(gtk.Label(), True, True, 0)
progress_vbox = gtk.VBox(False, 2)
progress_vbox.pack_start(status_box, False, False, 0)
progress_vbox.pack_start(remaining_box, False, False, 0)
progress_vbox.pack_start(passed_box, False, False, 0)
if frame_rates_match == False:
progress_vbox.pack_start(guiutils.get_pad_label(10, 10), False, False, 0)
progress_vbox.pack_start(warning_box, False, False, 0)
progress_vbox.pack_start(guiutils.get_pad_label(10, 10), False, False, 0)
progress_vbox.pack_start(dialog.progress_bar, False, False, 0)
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(12, 12, 12, 12)
alignment.add(progress_vbox)
dialog.vbox.pack_start(alignment, True, True, 0)
dialog.set_default_size(500, 125)
alignment.show_all()
dialog.set_has_separator(False)
dialog.connect('response', callback)
dialog.show()
return dialog
def no_good_rander_range_info():
primary_txt = _("Render range not defined!")
secondary_txt = _("Define render range using Mark In and Mark Out points\nor select range option 'Sequence length' to start rendering.")
dialogutils.warning_message(primary_txt, secondary_txt, gui.editor_window.window)
def load_ffmpeg_opts_dialog(callback, opts_extension):
dialog = gtk.FileChooserDialog(_("Load Render Args File"), None,
gtk.FILE_CHOOSER_ACTION_OPEN,
(_("Cancel").encode('utf-8'), gtk.RESPONSE_REJECT,
_("OK").encode('utf-8'), gtk.RESPONSE_ACCEPT), None)
dialog.set_action(gtk.FILE_CHOOSER_ACTION_OPEN)
dialog.set_select_multiple(False)
file_filter = gtk.FileFilter()
file_filter.set_name(opts_extension + " files")
file_filter.add_pattern("*" + opts_extension)
dialog.add_filter(file_filter)
dialog.connect('response', callback)
dialog.show()
def save_ffmpeg_opts_dialog(callback, opts_extension):
dialog = gtk.FileChooserDialog(_("Save Render Args As"), None,
gtk.FILE_CHOOSER_ACTION_SAVE,
(_("Cancel").encode('utf-8'), gtk.RESPONSE_REJECT,
_("Save").encode('utf-8'), gtk.RESPONSE_ACCEPT), None)
dialog.set_action(gtk.FILE_CHOOSER_ACTION_SAVE)
dialog.set_current_name("untitled" + opts_extension)
dialog.set_do_overwrite_confirmation(True)
dialog.set_select_multiple(False)
file_filter = gtk.FileFilter()
file_filter.set_name(opts_extension + " files")
file_filter.add_pattern("*" + opts_extension)
dialog.add_filter(file_filter)
dialog.connect('response', callback)
dialog.show()
def clip_render_progress_dialog(callback, title, text, progress_bar, parent_window):
dialog = gtk.Dialog(title,
parent_window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(_("Cancel").encode('utf-8'), gtk.RESPONSE_REJECT))
dialog.text_label = gtk.Label(text)
dialog.text_label.set_use_markup(True)
text_box = gtk.HBox(False, 2)
text_box.pack_start(dialog.text_label,False, False, 0)
text_box.pack_start(gtk.Label(), True, True, 0)
status_box = gtk.HBox(False, 2)
status_box.pack_start(text_box, False, False, 0)
status_box.pack_start(gtk.Label(), True, True, 0)
progress_vbox = gtk.VBox(False, 2)
progress_vbox.pack_start(status_box, False, False, 0)
progress_vbox.pack_start(guiutils.get_pad_label(10, 10), False, False, 0)
progress_vbox.pack_start(progress_bar, False, False, 0)
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(12, 12, 12, 12)
alignment.add(progress_vbox)
dialog.vbox.pack_start(alignment, True, True, 0)
dialog.set_default_size(500, 125)
alignment.show_all()
dialog.set_has_separator(False)
dialog.connect('response', callback)
dialog.show()
return dialog
def show_slowmo_dialog(media_file, _response_callback):
folder, file_name = os.path.split(media_file.path)
name, ext = os.path.splitext(file_name)
dialog = gtk.Dialog(_("Render Slow/Fast Motion Video File"), None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
_("Render").encode('utf-8'), gtk.RESPONSE_ACCEPT))
media_file_label = gtk.Label(_("Source Media File: "))
media_name = gtk.Label("<b>" + media_file.name + "</b>")
media_name.set_use_markup(True)
SOURCE_PAD = 8
SOURCE_HEIGHT = 20
mf_row = guiutils.get_left_justified_box([media_file_label, guiutils.pad_label(SOURCE_PAD, SOURCE_HEIGHT), media_name])
mark_in = gtk.Label(_("<b>not set</b>"))
mark_out = gtk.Label(_("<b>not set</b>"))
if media_file.mark_in != -1:
mark_in = gtk.Label("<b>" + utils.get_tc_string(media_file.mark_in) + "</b>")
if media_file.mark_out != -1:
mark_out = gtk.Label("<b>" + utils.get_tc_string(media_file.mark_out) + "</b>")
mark_in.set_use_markup(True)
mark_out.set_use_markup(True)
fb_widgets = utils.EmptyClass()
fb_widgets.file_name = gtk.Entry()
fb_widgets.file_name.set_text(name + "_MOTION")
fb_widgets.extension_label = gtk.Label()
fb_widgets.extension_label.set_size_request(45, 20)
name_row = gtk.HBox(False, 4)
name_row.pack_start(fb_widgets.file_name, True, True, 0)
name_row.pack_start(fb_widgets.extension_label, False, False, 4)
fb_widgets.out_folder = gtk.FileChooserButton(_("Select Target Folder"))
fb_widgets.out_folder.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
fb_widgets.out_folder.set_current_folder(folder)
label = gtk.Label(_("Speed %:"))
adjustment = gtk.Adjustment(float(100), float(1), float(600), float(1))
fb_widgets.hslider = gtk.HScale()
fb_widgets.hslider.set_adjustment(adjustment)
fb_widgets.hslider.set_draw_value(False)
spin = gtk.SpinButton()
spin.set_numeric(True)
spin.set_adjustment(adjustment)
fb_widgets.hslider.set_digits(0)
spin.set_digits(0)
slider_hbox = gtk.HBox(False, 4)
slider_hbox.pack_start(fb_widgets.hslider, True, True, 0)
slider_hbox.pack_start(spin, False, False, 4)
slider_hbox.set_size_request(350,35)
hbox = gtk.HBox(False, 2)
hbox.pack_start(guiutils.pad_label(8, 8), False, False, 0)
hbox.pack_start(label, False, False, 0)
hbox.pack_start(slider_hbox, False, False, 0)
profile_selector = ProfileSelector()
profile_selector.fill_options()
profile_selector.widget.set_sensitive(True)
fb_widgets.out_profile_combo = profile_selector.widget
quality_selector = RenderQualitySelector()
fb_widgets.quality_cb = quality_selector.widget
# Encoding
encoding_selector = RenderEncodingSelector(quality_selector, fb_widgets.extension_label, None)
encoding_selector.encoding_selection_changed()
fb_widgets.encodings_cb = encoding_selector.widget
objects_list = gtk.TreeStore(str, bool)
objects_list.append(None, [_("Full Source Length"), True])
if media_file.mark_in != -1 and media_file.mark_out != -1:
range_available = True
else:
range_available = False
objects_list.append(None, [_("Source Mark In to Mark Out"), range_available])
fb_widgets.render_range = gtk.ComboBox(objects_list)
renderer_text = gtk.CellRendererText()
fb_widgets.render_range.pack_start(renderer_text, True)
fb_widgets.render_range.add_attribute(renderer_text, "text", 0)
fb_widgets.render_range.add_attribute(renderer_text, 'sensitive', 1)
fb_widgets.render_range.set_active(0)
fb_widgets.render_range.show()
# To update rendered length display
clip_length = _get_rendered_slomo_clip_length(media_file, fb_widgets.render_range, 100)
clip_length_label = gtk.Label(utils.get_tc_string(clip_length))
fb_widgets.hslider.connect("value-changed", _slomo_speed_changed, media_file, fb_widgets.render_range, clip_length_label)
fb_widgets.render_range.connect("changed", _slomo_range_changed, media_file, fb_widgets.hslider, clip_length_label)
# Build gui
vbox = gtk.VBox(False, 2)
vbox.pack_start(mf_row, False, False, 0)
vbox.pack_start(guiutils.get_left_justified_box([gtk.Label(_("Source Mark In: ")), guiutils.pad_label(SOURCE_PAD, SOURCE_HEIGHT), mark_in]), False, False, 0)
vbox.pack_start(guiutils.get_left_justified_box([gtk.Label(_("Source_Mark Out: ")), guiutils.pad_label(SOURCE_PAD, SOURCE_HEIGHT), mark_out]), False, False, 0)
vbox.pack_start(guiutils.pad_label(18, 12), False, False, 0)
vbox.pack_start(hbox, False, False, 0)
vbox.pack_start(guiutils.pad_label(18, 12), False, False, 0)
vbox.pack_start(guiutils.get_two_column_box(gtk.Label(_("Target File:")), name_row, 120), False, False, 0)
vbox.pack_start(guiutils.get_two_column_box(gtk.Label(_("Target Folder:")), fb_widgets.out_folder, 120), False, False, 0)
vbox.pack_start(guiutils.get_two_column_box(gtk.Label(_("Target Profile:")), fb_widgets.out_profile_combo, 200), False, False, 0)
vbox.pack_start(guiutils.get_two_column_box(gtk.Label(_("Target Encoding:")), fb_widgets.encodings_cb, 200), False, False, 0)
vbox.pack_start(guiutils.get_two_column_box(gtk.Label(_("Target Quality:")), fb_widgets.quality_cb, 200), False, False, 0)
vbox.pack_start(guiutils.pad_label(18, 12), False, False, 0)
vbox.pack_start(guiutils.get_two_column_box(gtk.Label(_("Render Range:")), fb_widgets.render_range, 180), False, False, 0)
vbox.pack_start(guiutils.get_two_column_box(gtk.Label(_("Rendered Clip Length:")), clip_length_label, 180), False, False, 0)
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(6, 24, 24, 24)
alignment.add(vbox)
dialog.vbox.pack_start(alignment, True, True, 0)
dialogutils.default_behaviour(dialog)
dialog.connect('response', _response_callback, fb_widgets, media_file)
dialog.show_all()
def _slomo_speed_changed(slider, media_file, range_combo, length_label):
clip_length = _get_rendered_slomo_clip_length(media_file, range_combo, slider.get_adjustment().get_value())
length_label.set_text(utils.get_tc_string(clip_length))
def _slomo_range_changed(range_combo, media_file, slider, length_label):
clip_length = _get_rendered_slomo_clip_length(media_file, range_combo, slider.get_adjustment().get_value())
length_label.set_text(utils.get_tc_string(clip_length))
def _get_rendered_slomo_clip_length(media_file, range_combo, speed):
if range_combo.get_active() == 1:
orig_len = media_file.mark_out - media_file.mark_in + 1 # +1 mark out incl
else:
orig_len = media_file.length
return int((float(orig_len) * 100.0) / float(speed))
# ----------------------------------------------------------- widgets
class RenderQualitySelector():
"""
Component displays quality option relevant for encoding slection.
"""
def __init__(self):
self.widget = gtk.combo_box_new_text()
self.widget.set_tooltip_text(_("Select Render quality"))
def update_quality_selection(self, enc_index):
encoding = renderconsumer.encoding_options[enc_index]
self.widget.get_model().clear()
for quality_option in encoding.quality_options:
self.widget.append_text(quality_option.name)
if encoding.quality_default_index != None:
self.widget.set_active(encoding.quality_default_index)
else:
self.widget.set_active(0)
class RenderEncodingSelector():
def __init__(self, quality_selector, extension_label, audio_desc_label):
self.widget = gtk.combo_box_new_text()
for encoding in renderconsumer.encoding_options:
self.widget.append_text(encoding.name)
self.widget.set_active(0)
self.widget.connect("changed",
lambda w,e: self.encoding_selection_changed(),
None)
self.widget.set_tooltip_text(_("Select Render encoding"))
self.quality_selector = quality_selector
self.extension_label = extension_label
self.audio_desc_label = audio_desc_label
def encoding_selection_changed(self):
enc_index = self.widget.get_active()
self.quality_selector.update_quality_selection(enc_index)
encoding = renderconsumer.encoding_options[enc_index]
self.extension_label.set_text("." + encoding.extension)
if self.audio_desc_label != None:
self.audio_desc_label.set_markup(encoding.get_audio_description())
class PresetEncodingsSelector():
def __init__(self, selection_changed_callback):
self.widget = gtk.combo_box_new_text()
for encoding in renderconsumer.non_user_encodings:
self.widget.append_text(encoding.name)
self.widget.set_active(0)
self.widget.set_sensitive(False)
self.widget.connect("changed",
lambda w,e: selection_changed_callback(),
None)
class ProfileSelector():
def __init__(self, out_profile_changed_callback=None):
self.widget = gtk.combo_box_new_text() # filled later when current sequence known
if out_profile_changed_callback != None:
self.widget.connect('changed', lambda w: out_profile_changed_callback())
self.widget.set_sensitive(False)
self.widget.set_tooltip_text(_("Select render profile"))
def fill_options(self):
self.widget.get_model().clear()
self.widget.append_text(current_sequence().profile.description())
profiles = mltprofiles.get_profiles()
for profile in profiles:
self.widget.append_text(profile[0])
self.widget.set_active(0)
class ProfileInfoBox(gtk.VBox):
def __init__(self):
gtk.VBox.__init__(self, False, 2)
self.add(gtk.Label()) # This is removed when we have data to fill this
def display_info(self, info_panel):
info_box_children = self.get_children()
for child in info_box_children:
self.remove(child)
self.add(info_panel)
self.show_all()
def get_range_selection_combo():
range_cb = gtk.combo_box_new_text()
range_cb.append_text(_("Full Length"))
range_cb.append_text(_("Marked Range"))
range_cb.set_active(0)
return range_cb
# ------------------------------------------------------------ panels
def get_render_panel_left(render_widgets, add_audio_panel, normal_height):
file_opts_panel = guiutils.get_named_frame(_("File"), render_widgets.file_panel.vbox, 4)
render_type_panel = guiutils.get_named_frame(_("Render Type"), render_widgets.render_type_panel.vbox, 4)
profile_panel = guiutils.get_named_frame(_("Render Profile"), render_widgets.profile_panel.vbox, 4)
encoding_panel = guiutils.get_named_frame(_("Encoding Format"), render_widgets.encoding_panel.vbox, 4)
render_panel = gtk.VBox()
render_panel.pack_start(file_opts_panel, False, False, 0)
render_panel.pack_start(render_type_panel, False, False, 0)
render_panel.pack_start(profile_panel, False, False, 0)
render_panel.pack_start(encoding_panel, False, False, 0)
render_panel.pack_start(gtk.Label(), True, True, 0)
return render_panel
def get_render_panel_right(render_widgets, render_clicked_cb, to_queue_clicked_cb):
opts_panel = guiutils.get_named_frame(_("Render Args"), render_widgets.args_panel.vbox, 4)
bin_row = gtk.HBox()
bin_row.pack_start(guiutils.get_pad_label(10, 8), False, False, 0)
bin_row.pack_start(gtk.Label(_("Open File in Bin:")), False, False, 0)
bin_row.pack_start(guiutils.get_pad_label(10, 2), False, False, 0)
bin_row.pack_start(render_widgets.args_panel.open_in_bin, False, False, 0)
bin_row.pack_start(gtk.Label(), True, True, 0)
range_row = gtk.HBox()
range_row.pack_start(guiutils.get_pad_label(10, 8), False, False, 0)
range_row.pack_start(gtk.Label(_("Render Range:")), False, False, 0)
range_row.pack_start(guiutils.get_pad_label(10, 2), False, False, 0)
range_row.pack_start(render_widgets.range_cb, True, True, 0)
buttons_panel = gtk.HBox()
buttons_panel.pack_start(guiutils.get_pad_label(10, 8), False, False, 0)
buttons_panel.pack_start(render_widgets.reset_button, False, False, 0)
buttons_panel.pack_start(gtk.Label(), True, True, 0)
buttons_panel.pack_start(render_widgets.queue_button, False, False, 0)
buttons_panel.pack_start(gtk.Label(), True, True, 0)
buttons_panel.pack_start(render_widgets.render_button, False, False, 0)
render_widgets.queue_button.connect("clicked",
to_queue_clicked_cb,
None)
render_widgets.render_button.connect("clicked",
render_clicked_cb,
None)
render_panel = gtk.VBox()
render_panel.pack_start(opts_panel, True, True, 0)
render_panel.pack_start(guiutils.get_pad_label(10, 22), False, False, 0)
render_panel.pack_start(bin_row, False, False, 0)
render_panel.pack_start(range_row, False, False, 0)
render_panel.pack_start(guiutils.get_pad_label(10, 12), False, False, 0)
render_panel.pack_start(buttons_panel, False, False, 0)
return render_panel
class RenderFilePanel():
def __init__(self):
self.out_folder = gtk.FileChooserButton(_("Select Folder"))
self.out_folder.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
self.out_folder.set_current_folder(os.path.expanduser("~") + "/")
gui.render_out_folder = self.out_folder
out_folder_row = guiutils.get_two_column_box(gtk.Label(_("Folder:")), self.out_folder, 60)
self.movie_name = gtk.Entry()
self.movie_name.set_text("movie")
self.extension_label = gtk.Label()
name_box = gtk.HBox(False, 8)
name_box.pack_start(self.movie_name, True, True, 0)
name_box.pack_start(self.extension_label, False, False, 0)
movie_name_row = guiutils.get_two_column_box(gtk.Label(_("Name:")), name_box, 60)
self.vbox = gtk.VBox(False, 2)
self.vbox.pack_start(out_folder_row, False, False, 0)
self.vbox.pack_start(movie_name_row, False, False, 0)
self.out_folder.set_tooltip_text(_("Select folder to place rendered file in"))
self.movie_name.set_tooltip_text(_("Give name for rendered file"))
class RenderTypePanel():
def __init__(self, render_type_changed_callback, preset_selection_changed_callback):
self.type_label = gtk.Label(_("Type:"))
self.presets_label = gtk.Label(_("Presets:"))
self.type_combo = gtk.combo_box_new_text() # filled later when current sequence known
self.type_combo.append_text(_("User Defined"))
self.type_combo.append_text(_("Preset File type"))
self.type_combo.set_active(0)
self.type_combo.connect('changed', lambda w: render_type_changed_callback())
self.presets_selector = PresetEncodingsSelector(preset_selection_changed_callback)
self.vbox = gtk.VBox(False, 2)
self.vbox.pack_start(guiutils.get_two_column_box(self.type_label,
self.type_combo, 80),
False, False, 0)
self.vbox.pack_start(guiutils.get_two_column_box(self.presets_label,
self.presets_selector.widget, 80),
False, False, 0)
class RenderProfilePanel():
def __init__(self, out_profile_changed_callback):
self.use_project_label = gtk.Label(_("Use Project Profile:"))
self.use_args_label = gtk.Label(_("Render using args:"))
self.use_project_profile_check = gtk.CheckButton()
self.use_project_profile_check.set_active(True)
self.use_project_profile_check.connect("toggled", self.use_project_check_toggled)
self.out_profile_combo = ProfileSelector(out_profile_changed_callback)
self.out_profile_info_box = ProfileInfoBox() # filled later when current sequence known
use_project_profile_row = gtk.HBox()
use_project_profile_row.pack_start(self.use_project_label, False, False, 0)
use_project_profile_row.pack_start(self.use_project_profile_check, False, False, 0)
use_project_profile_row.pack_start(gtk.Label(), True, True, 0)
self.use_project_profile_check.set_tooltip_text(_("Select used project profile for rendering"))
self.out_profile_info_box.set_tooltip_text(_("Render profile info"))
self.vbox = gtk.VBox(False, 2)
self.vbox.pack_start(use_project_profile_row, False, False, 0)
self.vbox.pack_start(self.out_profile_combo.widget, False, False, 0)
self.vbox.pack_start(self.out_profile_info_box, False, False, 0)
def set_sensitive(self, value):
self.use_project_profile_check.set_sensitive(value)
self.use_project_label.set_sensitive(value)
self.out_profile_combo.widget.set_sensitive(value)
def use_project_check_toggled(self, checkbutton):
self.out_profile_combo.widget.set_sensitive(checkbutton.get_active() == False)
if checkbutton.get_active() == True:
self.out_profile_combo.widget.set_active(0)
class RenderEncodingPanel():
def __init__(self, extension_label):
self.quality_selector = RenderQualitySelector()
self.quality_selector.widget.set_size_request(110, 34)
self.quality_selector.update_quality_selection(0)
self.audio_desc = gtk.Label()
self.encoding_selector = RenderEncodingSelector(self.quality_selector,
extension_label,
self.audio_desc)
self.encoding_selector.encoding_selection_changed()
self.speaker_image = gtk.image_new_from_file(respaths.IMAGE_PATH + "audio_desc_icon.png")
quality_row = gtk.HBox()
quality_row.pack_start(self.quality_selector.widget, False, False, 0)
quality_row.pack_start(gtk.Label(), True, False, 0)
quality_row.pack_start(self.speaker_image, False, False, 0)
quality_row.pack_start(self.audio_desc, False, False, 0)
quality_row.pack_start(gtk.Label(), True, False, 0)
self.vbox = gtk.VBox(False, 2)
self.vbox.pack_start(self.encoding_selector.widget, False, False, 0)
self.vbox.pack_start(quality_row, False, False, 0)
def set_sensitive(self, value):
self.quality_selector.widget.set_sensitive(value)
self.audio_desc.set_sensitive(value)
self.speaker_image.set_sensitive(value)
self.encoding_selector.widget.set_sensitive(value)
class RenderArgsPanel():
def __init__(self, normal_height, save_args_callback,
load_args_callback, display_selection_callback):
self.display_selection_callback = display_selection_callback
self.use_project_label = gtk.Label(_("Use Project Profile:"))
self.use_args_label = gtk.Label(_("Render using args:"))
self.use_args_check = gtk.CheckButton()
self.use_args_check.connect("toggled", self.use_args_toggled)
self.opts_save_button = gtk.Button()
icon = gtk.image_new_from_stock(gtk.STOCK_SAVE, gtk.ICON_SIZE_MENU)
self.opts_save_button.set_image(icon)
self.opts_save_button.connect("clicked", lambda w: save_args_callback())
self.opts_save_button.set_sensitive(False)
self.opts_load_button = gtk.Button()
icon = gtk.image_new_from_stock(gtk.STOCK_OPEN, gtk.ICON_SIZE_MENU)
self.opts_load_button.set_image(icon)
self.opts_load_button.connect("clicked", lambda w: load_args_callback())
self.load_selection_button = gtk.Button(_("Load Selection"))
self.load_selection_button.set_sensitive(False)
self.load_selection_button.connect("clicked", lambda w: self.display_selection_callback())
self.opts_load_button.set_sensitive(False)
self.ext_label = gtk.Label(_("Ext.:"))
self.ext_label.set_sensitive(False)
self.ext_entry = gtk.Entry()
self.ext_entry.set_width_chars(5)
self.ext_entry.set_sensitive(False)
self.opts_view = gtk.TextView()
self.opts_view.set_sensitive(False)
self.opts_view.set_pixels_above_lines(2)
self.opts_view.set_left_margin(2)
self.open_in_bin = gtk.CheckButton()
use_opts_row = gtk.HBox()
use_opts_row.pack_start(self.use_args_label, False, False, 0)
use_opts_row.pack_start(self.use_args_check, False, False, 0)
use_opts_row.pack_start(gtk.Label(), True, True, 0)
use_opts_row.pack_start(self.opts_load_button, False, False, 0)
use_opts_row.pack_start(self.opts_save_button, False, False, 0)
sw = gtk.ScrolledWindow()
sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
sw.add(self.opts_view)
if normal_height:
sw.set_size_request(*FFMPEG_VIEW_SIZE)
else:
w, h = FFMPEG_VIEW_SIZE
h = h - 30
sw.set_size_request(w, h)
scroll_frame = gtk.Frame()
scroll_frame.add(sw)
opts_buttons_row = gtk.HBox(False)
opts_buttons_row.pack_start(self.load_selection_button, False, False, 0)
opts_buttons_row.pack_start(gtk.Label(), True, True, 0)
opts_buttons_row.pack_start(self.ext_label, False, False, 0)
opts_buttons_row.pack_start(self.ext_entry, False, False, 0)
self.use_args_check.set_tooltip_text(_("Render using key=value rendering options"))
self.load_selection_button.set_tooltip_text(_("Load render options from currently selected encoding"))
self.opts_view.set_tooltip_text(_("Edit render options"))
self.opts_save_button.set_tooltip_text(_("Save Render Args into a text file"))
self.opts_load_button.set_tooltip_text(_("Load Render Args from a text file"))
self.vbox = gtk.VBox(False, 2)
self.vbox.pack_start(use_opts_row , False, False, 0)
self.vbox.pack_start(scroll_frame, True, True, 0)
self.vbox.pack_start(opts_buttons_row, False, False, 0)
def set_sensitive(self, value):
self.use_args_check.set_sensitive(value)
self.use_args_label.set_sensitive(value)
def display_encoding_args(self, profile, enc_index, qual_index):
encoding_option = renderconsumer.encoding_options[enc_index]
quality_option = encoding_option.quality_options[qual_index]
args_vals_list = encoding_option.get_args_vals_tuples_list(profile, quality_option)
text = ""
for arg_val in args_vals_list:
k, v = arg_val
line = str(k) + "=" + str(v) + "\n"
text = text + line
text_buffer = gtk.TextBuffer()
text_buffer.set_text(text)
self.opts_view.set_buffer(text_buffer)
self.ext_entry.set_text(encoding_option.extension)
def use_args_toggled(self, checkbutton):
active = checkbutton.get_active()
self.opts_view.set_sensitive(active)
self.load_selection_button.set_sensitive(active)
self.opts_save_button.set_sensitive(active)
self.opts_load_button.set_sensitive(active)
self.ext_label.set_sensitive(active)
self.ext_entry.set_sensitive(active)
if active == True:
self.display_selection_callback()
else:
self.opts_view.set_buffer(gtk.TextBuffer())
self.ext_entry.set_text("")
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module has methods that build panels from widgets. Created panels
are used to build gui at callsites.
"""
import pygtk
pygtk.require('2.0');
import gtk
import gui
import guicomponents
import guiutils
import editorpersistance
import mlttransitions
import renderconsumer
import respaths
import utils
HALF_ROW_WIDTH = 160 # Size of half row when using two column row components created here
EFFECT_PANEL_WIDTH_PAD = 20 # This is subtracted from notebgtk.Calendar ook width to get some component widths
TC_LABEL_WIDTH = 80 # in, out and length timecodes in monitor area top row
MEDIA_PANEL_MIN_ROWS = 2
MEDIA_PANEL_MAX_ROWS = 8
MEDIA_PANEL_DEFAULT_ROWS = 2
def get_media_files_panel(media_list_view, add_cb, del_cb, col_changed_cb, proxy_cb, filtering_cb):
# Create buttons and connect signals
add_media_b = gtk.Button(_("Add"))
del_media_b = gtk.Button(_("Delete"))
add_media_b.connect("clicked", add_cb, None)
del_media_b.connect("clicked", del_cb, None)
add_media_b.set_tooltip_text(_("Add Media File to Bin"))
del_media_b.set_tooltip_text(_("Delete Media File from Bin"))
proxy_b = gtk.Button()
proxy_b.set_image(gtk.image_new_from_file(respaths.IMAGE_PATH + "proxy_button.png"))
proxy_b.connect("clicked", proxy_cb, None)
proxy_b.set_tooltip_text(_("Render Proxy Files For Selected Media"))
gui.proxy_button = proxy_b
columns_img = gtk.image_new_from_file(respaths.IMAGE_PATH + "columns.png")
adj = gtk.Adjustment(value=editorpersistance.prefs.media_columns, lower=MEDIA_PANEL_MIN_ROWS, upper=MEDIA_PANEL_MAX_ROWS, step_incr=1)
spin = gtk.SpinButton(adj)
spin.set_numeric(True)
spin.set_size_request(40, 30)
spin.connect("changed", col_changed_cb)
all_pixbuf = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "show_all_files.png")
audio_pixbuf = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "show_audio_files.png")
graphics_pixbuf = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "show_graphics_files.png")
video_pixbuf = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "show_video_files.png")
imgseq_pixbuf = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "show_imgseq_files.png")
pattern_pixbuf = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "show_pattern_producers.png")
files_filter_launcher = guicomponents.ImageMenuLaunch(filtering_cb, [all_pixbuf, video_pixbuf, audio_pixbuf, graphics_pixbuf, imgseq_pixbuf, pattern_pixbuf], 20, 22)
files_filter_launcher.pixbuf_x = 3
files_filter_launcher.pixbuf_y = 9
gui.media_view_filter_selector = files_filter_launcher
buttons_box = gtk.HBox(False,1)
buttons_box.pack_start(add_media_b, True, True, 0)
buttons_box.pack_start(del_media_b, True, True, 0)
buttons_box.pack_start(proxy_b, False, False, 0)
buttons_box.pack_start(guiutils.get_pad_label(4, 4), False, False, 0)
buttons_box.pack_start(columns_img, False, False, 0)
buttons_box.pack_start(spin, False, False, 0)
buttons_box.pack_start(files_filter_launcher.widget, False, False, 0)
panel = gtk.VBox()
panel.pack_start(buttons_box, False, True, 0)
panel.pack_start(media_list_view, True, True, 0)
out_align = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
out_align.set_padding(4, 4, 0, 4)
out_align.add(panel)
return out_align
def get_bins_panel(bin_list_view, add_cb, delete_cb):
# Create buttons and connect signals
add_b = gtk.Button(_("Add"))
del_b = gtk.Button(_("Delete"))
add_b.connect("clicked", add_cb, None)
del_b.connect("clicked", delete_cb, None)
add_b.set_tooltip_text(_("Add Bin to Project"))
del_b.set_tooltip_text(_("Delete Bin from Project"))
buttons_box = gtk.HBox(True,1)
buttons_box.pack_start(add_b)
buttons_box.pack_start(del_b)
panel = gtk.VBox()
panel.pack_start(buttons_box, False, True, 0)
panel.pack_start(bin_list_view, True, True, 0)
return get_named_frame(_("Bins"), panel, 0, 0, 0)
def get_sequences_panel(sequence_list_view, edit_seq_cb, add_seq_cb, del_seq_cb):
# Create buttons and connect signals
add_b = gtk.Button(_("Add"))
del_b = gtk.Button(_("Delete"))
edit_b = gtk.Button(_("Edit"))
add_b.set_tooltip_text(_("Add new Sequence to Project"))
del_b.set_tooltip_text(_("Delete Sequence from Project"))
edit_b.set_tooltip_text(_("Start editing Sequence"))
edit_b.connect("clicked", edit_seq_cb, None)
add_b.connect("clicked", add_seq_cb, None)
del_b.connect("clicked", del_seq_cb, None)
buttons_box = gtk.HBox(True,1)
buttons_box.pack_start(edit_b)
buttons_box.pack_start(add_b)
buttons_box.pack_start(del_b)
panel = gtk.VBox()
panel.pack_start(buttons_box, False, True, 0)
panel.pack_start(sequence_list_view, True, True, 0)
return get_named_frame(_("Sequences"), panel, 4)
"""
def get_profile_info_panel(profile):
desc_label = gtk.Label(profile.description())
info = guicomponents.get_profile_info_small_box(profile)
panel = gtk.VBox()
panel.pack_start(guiutils.get_left_justified_box([desc_label]), False, True, 0)
panel.pack_start(info, False, True, 0)
return get_named_frame(_("Profile"), panel, 4)
"""
"""
def get_project_name_panel(project_name):
name_row = get_left_justified_box([gtk.Label(project_name)])
return get_named_frame(_("Name"), name_row, 4)
"""
def get_thumbnail_select_panel(current_folder_path):
texts_panel = get_two_text_panel(_("Select folder for new thumbnails."),
_("Old thumbnails in this or other projects will") +
_(" still be available,\nthis only affects thumnails that are created for new media.\n") +
_("\nSetting your home folder as thumbnails folder is not allowed."))
out_folder = gtk.FileChooserButton("Select Folder")
out_folder.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
if current_folder_path != None:
out_folder.set_current_folder(current_folder_path)
out_folder_align = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
out_folder_align.set_padding(12, 24, 12, 12)
out_folder_align.add(out_folder)
panel = gtk.VBox()
panel.pack_start(texts_panel, False, False, 0)
panel.pack_start(out_folder_align, False, False, 0)
return (panel, out_folder)
def get_render_folder_select_panel(current_folder_path):
texts_panel = get_two_text_panel(_("Select folder for rendered clips."),
_("Old rendered clips in this or other projects will") +
_(" still be available,\nthis only affects rendered files that are created from now on.\n") +
_("\nSetting your home folder as folder for rendered clips is not allowed."))
out_folder = gtk.FileChooserButton("Select Folder")
out_folder.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
if current_folder_path != None:
out_folder.set_current_folder(current_folder_path)
out_folder_align = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
out_folder_align.set_padding(12, 24, 12, 12)
out_folder_align.add(out_folder)
panel = gtk.VBox()
panel.pack_start(texts_panel, False, False, 0)
panel.pack_start(out_folder_align, False, False, 0)
return (panel, out_folder)
def _set_sensive_widgets(sensitive, list):
for widget in list:
widget.set_sensitive(sensitive)
def get_motion_render_progress_panel(file_name, progress_bar):
status_box = gtk.HBox(False, 2)
status_box.pack_start(gtk.Label(file_name),False, False, 0)
status_box.pack_start(gtk.Label(), True, True, 0)
progress_vbox = gtk.VBox(False, 2)
progress_vbox.pack_start(status_box, False, False, 0)
progress_vbox.pack_start(guiutils.get_pad_label(10, 10), False, False, 0)
progress_vbox.pack_start(progress_bar, False, False, 0)
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(12, 12, 12, 12)
alignment.add(progress_vbox)
return alignment
def get_named_frame(name, widget, left_padding=12, right_padding=6, right_out_padding=4):
"""
Gnome style named panel
"""
if name != None:
label = guiutils.bold_label(name)
label.set_justify(gtk.JUSTIFY_LEFT)
label_box = gtk.HBox()
label_box.pack_start(label, False, False, 0)
label_box.pack_start(gtk.Label(), True, True, 0)
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(right_padding, 0, left_padding, 0)
alignment.add(widget)
frame = gtk.VBox()
if name != None:
frame.pack_start(label_box, False, False, 0)
frame.pack_start(alignment, True, True, 0)
out_align = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
out_align.set_padding(4, 4, 0, right_out_padding)
out_align.add(frame)
return out_align
def get_two_text_panel(primary_txt, secondary_txt):
p_label = guiutils.bold_label(primary_txt)
s_label = gtk.Label(secondary_txt)
texts_pad = gtk.Label()
texts_pad.set_size_request(12,12)
pbox = gtk.HBox(False, 1)
pbox.pack_start(p_label, False, False, 0)
pbox.pack_start(gtk.Label(), True, True, 0)
sbox = gtk.HBox(False, 1)
sbox.pack_start(s_label, False, False, 0)
sbox.pack_start(gtk.Label(), True, True, 0)
text_box = gtk.VBox(False, 0)
text_box.pack_start(pbox, False, False, 0)
text_box.pack_start(texts_pad, False, False, 0)
text_box.pack_start(sbox, False, False, 0)
text_box.pack_start(gtk.Label(), True, True, 0)
align = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
align.set_padding(12, 0, 12, 12)
align.add(text_box)
return align
def get_file_properties_panel(data):
media_file, img, size, length, vcodec, acodec, channels, frequency, fps = data
row0 = get_two_column_box(get_bold_label(_("Name:")), gtk.Label(media_file.name))
row00 = get_two_column_box(get_bold_label(_("Path:")), gtk.Label(media_file.path))
row1 = get_two_column_box(get_bold_label(_("Image Size:")), gtk.Label(size))
row111 = get_two_column_box(get_bold_label(_("Frames Per Second:")), gtk.Label(fps))
row11 = get_two_column_box(get_bold_label(_("Playtime:")), gtk.Label(length))
row2 = get_two_column_box(get_bold_label(_("Video Codec:")), gtk.Label(vcodec))
row3 = get_two_column_box(get_bold_label(_("Audio Codec:")), gtk.Label(acodec))
row4 = get_two_column_box(get_bold_label(_("Audio Channels:")), gtk.Label(channels))
row5 = get_two_column_box(get_bold_label(_("Audio Sample Rate:")), gtk.Label(frequency))
vbox = gtk.VBox(False, 2)
vbox.pack_start(img, False, False, 0)
vbox.pack_start(guiutils.get_pad_label(12, 16), False, False, 0)
vbox.pack_start(row0, False, False, 0)
vbox.pack_start(row00, False, False, 0)
vbox.pack_start(row1, False, False, 0)
vbox.pack_start(row111, False, False, 0)
vbox.pack_start(row11, False, False, 0)
vbox.pack_start(row2, False, False, 0)
vbox.pack_start(row3, False, False, 0)
vbox.pack_start(row4, False, False, 0)
vbox.pack_start(row5, False, False, 0)
vbox.pack_start(gtk.Label(), True, True, 0)
return vbox
def get_clip_properties_panel(data):
length, size, path, vcodec, acodec = data
row1 = get_two_column_box(get_bold_label(_("Clip Length:")), gtk.Label(length))
row2 = get_two_column_box(get_bold_label(_("Image Size:")), gtk.Label(size))
row3 = get_two_column_box(get_bold_label(_("Media Path:")), gtk.Label(path))
row4 = get_two_column_box(get_bold_label(_("Video Codec:")), gtk.Label(vcodec))
row5 = get_two_column_box(get_bold_label(_("Audio Codec:")), gtk.Label(acodec))
vbox = gtk.VBox(False, 2)
vbox.pack_start(row1, False, False, 0)
vbox.pack_start(row2, False, False, 0)
vbox.pack_start(row3, False, False, 0)
vbox.pack_start(row4, False, False, 0)
vbox.pack_start(row5, False, False, 0)
vbox.pack_start(gtk.Label(), True, True, 0)
return vbox
def get_add_compositor_panel(current_sequence, data):
clip, track, compositor_index, clip_index = data
track_combo = gtk.combo_box_new_text()
default_track_index = -1
for i in range(current_sequence.first_video_index, track.id):
add_track = current_sequence.tracks[i]
text = "Track " + utils.get_track_name(add_track, current_sequence)
track_combo.append_text(text)
default_track_index += 1
track_combo.set_active(default_track_index)
track_combo.set_size_request(HALF_ROW_WIDTH, 30)
vbox = gtk.VBox(False, 2)
vbox.pack_start(get_two_column_box(gtk.Label(_("Composite clip on:")), track_combo), False, False, 0)
return (vbox, track_combo)
def get_transition_panel(trans_data):
type_combo_box = gtk.combo_box_new_text()
name, t_service_id = mlttransitions.rendered_transitions[0]
type_combo_box.append_text(name)
name, t_service_id = mlttransitions.rendered_transitions[1]
type_combo_box.append_text(name)
name, t_service_id = mlttransitions.rendered_transitions[2]
type_combo_box.append_text(name)
type_combo_box.set_active(0)
type_row = get_two_column_box(gtk.Label(_("Type:")),
type_combo_box)
wipe_luma_combo_box = gtk.combo_box_new_text()
keys = mlttransitions.wipe_lumas.keys()
keys.sort()
for k in keys:
wipe_luma_combo_box.append_text(k)
wipe_luma_combo_box.set_active(0)
wipe_label = gtk.Label(_("Wipe Pattern:"))
wipe_row = get_two_column_box(wipe_label,
wipe_luma_combo_box)
color_button = gtk.ColorButton(gtk.gdk.Color(0.0, 0.0, 0.0))
color_button_box = guiutils.get_left_justified_box([color_button])
color_label = gtk.Label(_("Dip Color:"))
color_row = get_two_column_box(color_label, color_button_box)
wipe_luma_combo_box.set_sensitive(False)
color_button.set_sensitive(False)
wipe_label.set_sensitive(False)
color_label.set_sensitive(False)
transition_type_widgets = (type_combo_box, wipe_luma_combo_box, color_button, wipe_label, color_label)
type_combo_box.connect("changed",
lambda w,e: _transition_type_changed(transition_type_widgets),
None)
length_entry = gtk.Entry()
length_entry.set_text(str(30))
length_row = get_two_column_box(gtk.Label(_("Length:")),
length_entry)
filler = gtk.Label()
filler.set_size_request(10,10)
out_clip_label = gtk.Label(_("From Clip Handle:"))
out_clip_value = gtk.Label(trans_data["from_handle"])
in_clip_label = gtk.Label(_("To Clip Handle:"))
in_clip_value = gtk.Label(trans_data["to_handle"])
max_label = gtk.Label(_("Max. Transition Length:"))
max_value = gtk.Label(trans_data["max_length"])
out_handle_row = get_two_column_box(out_clip_label,
out_clip_value)
in_handle_row = get_two_column_box(in_clip_label,
in_clip_value)
max_row = get_two_column_box(max_label,
max_value)
# Encoding widgets
encodings_cb = gtk.combo_box_new_text()
for encoding in renderconsumer.encoding_options:
encodings_cb.append_text(encoding.name)
encodings_cb.set_active(0)
quality_cb = gtk.combo_box_new_text()
transition_widgets = (encodings_cb, quality_cb)
encodings_cb.connect("changed",
lambda w,e: _transition_encoding_changed(transition_widgets),
None)
_fill_transition_quality_combo_box(transition_widgets)
# Build panel
edit_vbox = gtk.VBox(False, 2)
edit_vbox.pack_start(type_row, False, False, 0)
edit_vbox.pack_start(length_row, False, False, 0)
edit_vbox.pack_start(wipe_row, False, False, 0)
edit_vbox.pack_start(color_row, False, False, 0)
data_vbox = gtk.VBox(False, 2)
data_vbox.pack_start(out_handle_row, False, False, 0)
data_vbox.pack_start(in_handle_row, False, False, 0)
data_vbox.pack_start(max_row, False, False, 0)
enconding_vbox = gtk.VBox(False, 2)
enconding_vbox.pack_start(encodings_cb, False, False, 0)
enconding_vbox.pack_start(quality_cb, False, False, 0)
vbox = gtk.VBox(False, 2)
vbox.pack_start(get_named_frame(_("Transition Options"), edit_vbox))
vbox.pack_start(get_named_frame(_("Clips info"), data_vbox))
vbox.pack_start(get_named_frame(_("Encoding"), enconding_vbox))
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(12, 24, 12, 12)
alignment.add(vbox)
return (alignment, type_combo_box, length_entry, encodings_cb, quality_cb, wipe_luma_combo_box, color_button)
def get_fade_panel(fade_data):
type_combo_box = gtk.combo_box_new_text()
type_combo_box.append_text(_("Fade In"))
type_combo_box.append_text(_("Fade Out"))
type_combo_box.set_active(0)
type_row = get_two_column_box(gtk.Label(_("Type:")),
type_combo_box)
color_button = gtk.ColorButton(gtk.gdk.Color(0.0, 0.0, 0.0))
color_button_box = guiutils.get_left_justified_box([color_button])
color_label = gtk.Label(_("Color:"))
color_row = get_two_column_box(color_label, color_button_box)
length_entry = gtk.Entry()
length_entry.set_text(str(30))
length_row = get_two_column_box(gtk.Label(_("Length:")),
length_entry)
# Encoding widgets
encodings_cb = gtk.combo_box_new_text()
for encoding in renderconsumer.encoding_options:
encodings_cb.append_text(encoding.name)
encodings_cb.set_active(0)
quality_cb = gtk.combo_box_new_text()
transition_widgets = (encodings_cb, quality_cb)
encodings_cb.connect("changed",
lambda w,e: _transition_encoding_changed(transition_widgets),
None)
_fill_transition_quality_combo_box(transition_widgets)
# Build panel
edit_vbox = gtk.VBox(False, 2)
edit_vbox.pack_start(type_row, False, False, 0)
edit_vbox.pack_start(length_row, False, False, 0)
edit_vbox.pack_start(color_row, False, False, 0)
enconding_vbox = gtk.VBox(False, 2)
enconding_vbox.pack_start(encodings_cb, False, False, 0)
enconding_vbox.pack_start(quality_cb, False, False, 0)
vbox = gtk.VBox(False, 2)
vbox.pack_start(get_named_frame(_("Transition Options"), edit_vbox))
vbox.pack_start(get_named_frame(_("Encoding"), enconding_vbox))
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(12, 24, 12, 12)
alignment.add(vbox)
return (alignment, type_combo_box, length_entry, encodings_cb, quality_cb, color_button)
def _transition_encoding_changed(widgets):
_fill_transition_quality_combo_box(widgets)
def _fill_transition_quality_combo_box(widgets):
encodings_cb, quality_cb = widgets
enc_index = encodings_cb.get_active()
encoding = renderconsumer.encoding_options[enc_index]
quality_cb.get_model().clear()
for quality_option in encoding.quality_options:
quality_cb.append_text(quality_option.name)
if encoding.quality_default_index != None:
quality_cb.set_active(encoding.quality_default_index)
else:
quality_cb.set_active(0)
def _transition_type_changed(transition_type_widgets):
type_combo_box, wipe_luma_combo_box, color_button, wipe_label, color_label = transition_type_widgets
if type_combo_box.get_active() == 0:
wipe_luma_combo_box.set_sensitive(False)
color_button.set_sensitive(False)
wipe_label.set_sensitive(False)
color_label.set_sensitive(False)
elif type_combo_box.get_active() == 1:
wipe_luma_combo_box.set_sensitive(True)
color_button.set_sensitive(False)
wipe_label.set_sensitive(True)
color_label.set_sensitive(False)
else:
wipe_luma_combo_box.set_sensitive(False)
color_button.set_sensitive(True)
wipe_label.set_sensitive(False)
color_label.set_sensitive(True)
# -------------------------------------------------- guiutils
def get_bold_label(text):
return guiutils.bold_label(text)
def get_left_justified_box(widgets):
return guiutils.get_left_justified_box(widgets)
def get_two_column_box(widget1, widget2, left_width=HALF_ROW_WIDTH):
return guiutils.get_two_column_box(widget1, widget2, left_width)
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module contains main editor window object.
"""
import pygtk
pygtk.require('2.0');
import gtk
import pango
import app
import appconsts
import audiomonitoring
import batchrendering
import clipeffectseditor
import clipmenuaction
import compositeeditor
import dialogs
import dnd
import editevent
import editorpersistance
import editorstate
import exporting
import glassbuttons
import gui
import guicomponents
import guiutils
import medialinker
import medialog
import menuactions
import middlebar
import monitorevent
import respaths
import render
import rendergui
import panels
import patternproducer
from positionbar import PositionBar
import preferenceswindow
import projectaction
import projectinfogui
import proxyediting
import titler
import tlineaction
import tlinewidgets
import trackaction
import updater
import undo
# GUI size params
MEDIA_MANAGER_WIDTH = 250
MONITOR_AREA_WIDTH = 600 # defines app min width with NOTEBOOK_WIDTH 400 for small
MODE_BUTTON_ACTIVE_COLOR = "#9d9d9d"
MODE_BUTTON_PRELIGHT_COLOR = "#bdbdbd"
BINS_HEIGHT = 250
EFFECT_STACK_VIEW_HEIGHT = 160
EFFECT_VALUE_EDITOR_HEIGHT = 200
EFFECT_SELECT_EDITOR_HEIGHT = 140
IMG_PATH = None
# Cursors
OVERWRITE_CURSOR = None
INSERTMOVE_CURSOR = None
ONEROLL_CURSOR = None
ONEROLL_NO_EDIT_CURSOR = None
TWOROLL_CURSOR = None
TWOROLL_NO_EDIT_CURSOR = None
SLIDE_CURSOR = None
SLIDE_NO_EDIT_CURSOR = None
MULTIMOVE_CURSOR = None
def _b(button, icon, remove_relief=False):
button.set_image(icon)
button.set_property("can-focus", False)
if remove_relief:
button.set_relief(gtk.RELIEF_NONE)
def _toggle_image_switch(widget, icons):
not_pressed, pressed = icons
if widget.get_active() == True:
widget.set_image(pressed)
else:
widget.set_image(not_pressed)
class EditorWindow:
def __init__(self):
global IMG_PATH
IMG_PATH = respaths.IMAGE_PATH
# Read cursors
global INSERTMOVE_CURSOR, OVERWRITE_CURSOR, TWOROLL_CURSOR, ONEROLL_CURSOR, \
ONEROLL_NO_EDIT_CURSOR, TWOROLL_NO_EDIT_CURSOR, SLIDE_CURSOR, SLIDE_NO_EDIT_CURSOR, \
MULTIMOVE_CURSOR, MULTIMOVE_NO_EDIT_CURSOR
INSERTMOVE_CURSOR = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "insertmove_cursor.png")
OVERWRITE_CURSOR = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "overwrite_cursor.png")
TWOROLL_CURSOR = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "tworoll_cursor.png")
ONEROLL_CURSOR = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "oneroll_cursor.png")
SLIDE_CURSOR = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "slide_cursor.png")
ONEROLL_NO_EDIT_CURSOR = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "oneroll_noedit_cursor.png")
TWOROLL_NO_EDIT_CURSOR = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "tworoll_noedit_cursor.png")
SLIDE_NO_EDIT_CURSOR = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "slide_noedit_cursor.png")
MULTIMOVE_CURSOR = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "multimove_cursor.png")
MULTIMOVE_NO_EDIT_CURSOR = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "multimove_cursor.png")
# Window
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_icon_from_file(respaths.IMAGE_PATH + "flowbladeappicon.png")
self.window.set_border_width(5)
# To ask confirmation for shutdown
self.window.connect("delete-event", lambda w, e:app.shutdown())
# Player consumer has to be stopped and started when window resized
self.window.connect("window-state-event", lambda w, e:updater.refresh_player())
# Build menubar
# Menubar build resources
menu_actions = [
('FileMenu', None, _('_File')),
('New', None, _('_New...'), '<control>N', None, lambda a:projectaction.new_project()),
('Open', None, _('_Open...'), '<control>O', None, lambda a:projectaction.load_project()),
('OpenRecent', None, _('Open Recent')),
('Save', None, _('_Save'), '<control>S', None, lambda a:projectaction.save_project()),
('Save As', None, _('_Save As...'), None, None, lambda a:projectaction.save_project_as()),
('SaveSnapshot', None, _('Save Backup Snapshot...'), None, None, lambda a:projectaction.save_backup_snapshot()),
('ExportMenu', None, _('Export')),
('ExportMeltXML', None, _('MLT XML'), None, None, lambda a:exporting.MELT_XML_export()),
('ExportEDL', None, _('EDL CMX 3600'), None, None, lambda a:exporting.EDL_export()),
('ExportScreenshot', None, _('Current Frame'), None, None, lambda a:exporting.screenshot_export()),
('Close', None, _('_Close'), None, None, lambda a:projectaction.close_project()),
('Quit', None, _('_Quit'), '<control>Q', None, lambda a:app.shutdown()),
('EditMenu', None, _('_Edit')),
('Undo', None, _('_Undo'), '<control>Z', None, undo.do_undo_and_repaint),
('Redo', None, _('_Redo'), '<control>Y', None, undo.do_redo_and_repaint),
('AddFromMonitor', None, _('Add Monitor Clip')),
('AppendClip', None, _('Append'), None, None, lambda a:tlineaction.append_button_pressed()),
('InsertClip', None, _('Insert'), None, None, lambda a:tlineaction.insert_button_pressed()),
('ThreepointOverWriteClip', None, _('Three Point Overwrite'), None, None, lambda a:tlineaction.three_point_overwrite_pressed()),
('RangeOverWriteClip', None, _('Range Overwrite'), None, None, lambda a:tlineaction.range_overwrite_pressed()),
('CutClip', None, _('Cut Clip'), None, None, lambda a:tlineaction.cut_pressed()),
('DeleteClip', None, _('Lift'), None, None, lambda a:tlineaction.lift_button_pressed()),
('SpliceOutClip', None, _('Splice Out'), None, None, lambda a:tlineaction.splice_out_button_pressed()),
('ResyncSelected', None, _('Resync'), None, None, lambda a:tlineaction.resync_button_pressed()),
('SetSyncParent', None, _('Set Sync Parent'), None, None, lambda a:_this_is_not_used()),
('AddTransition', None, _('Add Single Track Transition'), None, None, lambda a:tlineaction.add_transition_menu_item_selected()),
('AddFade', None, _('Add Single Track Fade'), None, None, lambda a:tlineaction.add_fade_menu_item_selected()),
('ClearFilters', None, _('Clear Filters'), None, None, lambda a:clipmenuaction.clear_filters()),
('ChangeSequenceTracks', None, _('Change Sequence Tracks Count...'), None, None, lambda a:projectaction.change_sequence_track_count()),
('Watermark', None, _('Watermark...'), None, None, lambda a:menuactions.edit_watermark()),
('ProfilesManager', None, _('Profiles Manager'), None, None, lambda a:menuactions.profiles_manager()),
('Preferences', None, _('Preferences'), None, None, lambda a:preferenceswindow.preferences_dialog()),
('ViewMenu', None, _('View')),
('ProjectMenu', None, _('Project')),
('AddMediaClip', None, _('Add Media Clip...'), None, None, lambda a: projectaction.add_media_files()),
('AddImageSequence', None, _('Add Image Sequence...'), None, None, lambda a:projectaction.add_image_sequence()),
('CreateColorClip', None, _('Create Color Clip...'), None, None, lambda a:patternproducer.create_color_clip()),
('PatternProducersMenu', None, _('Create Pattern Producer')),
('CreateNoiseClip', None, _('Noise'), None, None, lambda a:patternproducer.create_noise_clip()),
('CreateBarsClip', None, _('EBU Bars'), None, None, lambda a:patternproducer.create_bars_clip()),
('CreateIsingClip', None, _('Ising'), None, None, lambda a:patternproducer.create_icing_clip()),
('CreateColorPulseClip', None, _('Color Pulse'), None, None, lambda a:patternproducer.create_color_pulse_clip()),
('LogClipRange', None, _('Log Marked Clip Range'), '<control>L', None, lambda a:medialog.log_range_clicked()),
('RecreateMediaIcons', None, _('Recreate Media Icons...'), None, None, lambda a:menuactions.recreate_media_file_icons()),
('RemoveUnusedMedia', None, _('Remove Unused Media...'), None, None, lambda a:projectaction.remove_unused_media()),
('JackAudio', None, _("JACK Audio..."), None, None, lambda a: menuactions.jack_output_managing()),
('ProxyManager', None, _('Proxy Manager'), None, None, lambda a:proxyediting.show_proxy_manager_dialog()),
('ProjectType', None, _("Change Project Type..."), None, None, lambda a:projectaction.change_project_type()),
('ProjectInfo', None, _('Project Info'), None, None, lambda a:menuactions.show_project_info()),
('RenderMenu', None, _('Render')),
('AddToQueue', None, _('Add To Batch Render Queue...'), None, None, lambda a:projectaction.add_to_render_queue()),
('BatchRender', None, _('Batch Render Queue'), None, None, lambda a:batchrendering.launch_batch_rendering()),
('Render', None, _('Render Timeline'), None, None, lambda a:projectaction.do_rendering()),
('ToolsMenu', None, _('Tools')),
('Titler', None, _('Titler'), None, None, lambda a:titler.show_titler()),
('AudioMix', None, _('Audio Mixer'), None, None, lambda a:audiomonitoring.show_audio_monitor()),
('MediaLink', None, _('Media Relinker'), None, None, lambda a:medialinker.display_linker()),
('HelpMenu', None, _('_Help')),
('QuickReference', None, _('Contents'), None, None, lambda a:menuactions.quick_reference()),
('Environment', None, _('Runtime Environment'), None, None, lambda a:menuactions.environment()),
('KeyboardShortcuts', None, _('Keyboard Shortcuts'), None, None, lambda a:dialogs.keyboard_shortcuts_dialog(self.window)),
('About', None, _('About'), None, None, lambda a:menuactions.about()),
('InsertMode', None, None, '1', None, lambda a:_this_is_not_used()),
('OverMode', None, None, '2', None, lambda a:_this_is_not_used()),
('OneRollMode', None, None, '3', None, lambda a:_this_is_not_used()),
('TwoRollMode', None, None, '4', None, lambda a:_this_is_not_used()),
('SlideMode', None, None, '5', None, lambda a:_this_is_not_used()),
('MultiMode', None, None, '6', None, lambda a:_this_is_not_used())
]
menu_string = """<ui>
<menubar name='MenuBar'>
<menu action='FileMenu'>
<menuitem action='New'/>
<menuitem action='Open'/>
<menu action='OpenRecent'/>
<menuitem action='Save'/>
<menuitem action='Save As'/>
<menuitem action='SaveSnapshot'/>
<separator/>
<menu action='ExportMenu'>
<menuitem action='ExportMeltXML'/>
<menuitem action='ExportScreenshot'/>
</menu>
<separator/>
<menuitem action='Close'/>
<menuitem action='Quit'/>
</menu>
<menu action='EditMenu'>
<menuitem action='Undo'/>
<menuitem action='Redo'/>
<separator/>
<menu action='AddFromMonitor'>
<menuitem action='AppendClip'/>
<menuitem action='InsertClip'/>
<menuitem action='ThreepointOverWriteClip'/>
<menuitem action='RangeOverWriteClip'/>
</menu>
<separator/>
<menuitem action='CutClip'/>
<separator/>
<menuitem action='SpliceOutClip'/>
<menuitem action='DeleteClip'/>
<menuitem action='ResyncSelected'/>
<menuitem action='ClearFilters'/>
<separator/>
<menuitem action='AddTransition'/>
<menuitem action='AddFade'/>
<separator/>
<menuitem action='ChangeSequenceTracks'/>
<menuitem action='Watermark'/>
<separator/>
<menuitem action='ProfilesManager'/>
<menuitem action='Preferences'/>
</menu>
<menu action='ViewMenu'>
</menu>
<menu action='ProjectMenu'>
<menuitem action='AddMediaClip'/>
<menuitem action='AddImageSequence'/>
<separator/>
<menuitem action='CreateColorClip'/>
<menu action='PatternProducersMenu'>
<menuitem action='CreateNoiseClip'/>
<menuitem action='CreateColorPulseClip'/>
<menuitem action='CreateIsingClip'/>
<menuitem action='CreateBarsClip'/>
</menu>
<separator/>
<menuitem action='LogClipRange'/>
<separator/>
<menuitem action='RecreateMediaIcons'/>
<menuitem action='RemoveUnusedMedia'/>
<separator/>
<menuitem action='ProxyManager'/>
</menu>
<menu action='RenderMenu'>
<menuitem action='AddToQueue'/>
<menuitem action='BatchRender'/>
<separator/>
<menuitem action='Render'/>
</menu>
<menu action='ToolsMenu'>
<menuitem action='Titler'/>
<menuitem action='AudioMix'/>
<separator/>
<menuitem action='MediaLink'/>
</menu>
<menu action='HelpMenu'>
<menuitem action='QuickReference'/>
<menuitem action='KeyboardShortcuts'/>
<menuitem action='Environment'/>
<separator/>
<menuitem action='About'/>
</menu>
</menubar>
</ui>"""
# Create global action group
action_group = gtk.ActionGroup('WindowActions')
action_group.add_actions(menu_actions, user_data=None)
# Create UIManager and add accelators to window
ui = gtk.UIManager()
ui.insert_action_group(action_group, 0)
ui.add_ui_from_string(menu_string)
accel_group = ui.get_accel_group()
self.window.add_accel_group(accel_group)
# Get menu bar
self.menubar = ui.get_widget('/MenuBar')
# Set reference to UI manager and acclegroup
self.uimanager = ui
self.accel_group = accel_group
# Add recent projects to menu
editorpersistance.fill_recents_menu_widget(ui.get_widget('/MenuBar/FileMenu/OpenRecent'), projectaction.open_recent_project)
# Disable audio mixer if not available
if editorstate.audio_monitoring_available == False:
ui.get_widget('/MenuBar/ToolsMenu/AudioMix').set_sensitive(False)
# Menu box
menu_vbox = gtk.VBox(False, 0)
menu_vbox.pack_start(self.menubar, False, True, 0)
# Media manager
self.bin_list_view = guicomponents.BinListView(
projectaction.bin_selection_changed,
projectaction.bin_name_edited)
dnd.connect_bin_tree_view(self.bin_list_view.treeview, projectaction.move_files_to_bin)
self.bin_list_view.set_property("can-focus", True)
bins_panel = panels.get_bins_panel(self.bin_list_view,
lambda w,e: projectaction.add_new_bin(),
lambda w,e: projectaction.delete_selected_bin())
bins_panel.set_size_request(MEDIA_MANAGER_WIDTH, BINS_HEIGHT)
self.media_list_view = guicomponents.MediaPanel(projectaction.media_file_menu_item_selected,
updater.set_and_display_monitor_media_file)
view = gtk.Viewport()
view.add(self.media_list_view.widget)
view.set_shadow_type(gtk.SHADOW_NONE)
self.media_scroll_window = gtk.ScrolledWindow()
self.media_scroll_window.add(view)
#self.media_scroll_window.add_with_viewport(self.media_list_view.widget)
self.media_scroll_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.media_scroll_window.set_size_request(guicomponents.MEDIA_OBJECT_WIDGET_WIDTH * 2 + 70, guicomponents.MEDIA_OBJECT_WIDGET_HEIGHT)
#self.media_scroll_window.set_shadow_type(gtk.SHADOW_NONE)
self.media_scroll_window.show_all()
media_panel = panels.get_media_files_panel(
self.media_scroll_window,
lambda w,e: projectaction.add_media_files(),
lambda w,e: projectaction.delete_media_files(),
lambda a: self.media_list_view.columns_changed(a),
lambda w,e: proxyediting.create_proxy_files_pressed(),
projectaction.media_filtering_select_pressed)
self.mm_paned = gtk.HPaned()
self.mm_paned.pack1(bins_panel, resize=True, shrink=True)
self.mm_paned.pack2(media_panel, resize=True, shrink=False)
mm_panel = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
mm_panel.set_padding(2, 2, 6, 2)
mm_panel.add(self.mm_paned)
# Effects
self.effect_select_list_view = guicomponents.FilterListView()
self.effect_select_combo_box = gtk.combo_box_new_text()
self.effect_select_list_view.treeview.connect("row-activated", clipeffectseditor.effect_select_row_double_clicked)
dnd.connect_effects_select_tree_view(self.effect_select_list_view.treeview)
clip_editor_panel = clipeffectseditor.get_clip_effects_editor_panel(
self.effect_select_combo_box,
self.effect_select_list_view)
clipeffectseditor.widgets.effect_stack_view.treeview.connect("button-press-event",
clipeffectseditor.filter_stack_button_press)
effects_editor_panel = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
effects_editor_panel.set_padding(0, 0, 4, 0)
effects_editor_panel.add(clipeffectseditor.widgets.value_edit_frame)
effects_hbox = gtk.HBox()
effects_hbox.set_border_width(5)
effects_hbox.pack_start(clip_editor_panel, False, False, 0)
effects_hbox.pack_start(effects_editor_panel, True, True, 0)
self.effects_panel = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
self.effects_panel.set_padding(2, 2, 2, 2)
self.effects_panel.add(effects_hbox)
# Compositors
compositor_clip_panel = compositeeditor.get_compositor_clip_panel()
compositor_editor_panel = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
compositor_editor_panel.set_padding(0, 0, 4, 0)
compositor_editor_panel.add(compositeeditor.widgets.value_edit_frame)
compositors_hbox = gtk.HBox()
compositors_hbox.set_border_width(5)
compositors_hbox.pack_start(compositor_clip_panel, False, False, 0)
compositors_hbox.pack_start(compositor_editor_panel, True, True, 0)
self.compositors_panel = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
self.compositors_panel.set_padding(0, 0, 0, 0)
self.compositors_panel.add(compositors_hbox)
# Render
normal_height = True
if appconsts.TOP_ROW_HEIGHT < 500: # small screens have no space to display this
normal_height = False
add_audio_desc = True
if editorstate.SCREEN_HEIGHT < 863:
add_audio_desc = False
try:
render.create_widgets(normal_height)
render_panel_left = rendergui.get_render_panel_left(
render.widgets,
add_audio_desc,
normal_height)
except IndexError:
print "No rendering options found"
render_panel_left = None
# 'None' here means that no possible rendering options were available
# and creating panel failed. Inform user of this and hide render GUI
if render_panel_left == None:
render_hbox = gtk.VBox(False, 5)
render_hbox.pack_start(gtk.Label("Rendering disabled."), False, False, 0)
render_hbox.pack_start(gtk.Label("No available rendering options found."), False, False, 0)
render_hbox.pack_start(gtk.Label("See Help->Environment->Render Options for details."), False, False, 0)
render_hbox.pack_start(gtk.Label("Install codecs to make rendering available."), False, False, 0)
render_hbox.pack_start(gtk.Label(" "), True, True, 0)
else: # all is good
render_panel_right = rendergui.get_render_panel_right(render.widgets,
lambda w,e: projectaction.do_rendering(),
lambda w,e: projectaction.add_to_render_queue())
render_hbox = gtk.HBox(True, 5)
render_hbox.pack_start(render_panel_left, True, True, 0)
render_hbox.pack_start(render_panel_right, True, True, 0)
render_panel = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
render_panel.set_padding(2, 6, 8, 6)
render_panel.add(render_hbox)
# Media log events List
media_log_events_list_view = medialog.get_media_log_list_view()
events_panel = medialog.get_media_log_events_panel(media_log_events_list_view)
media_log_vbox = gtk.HBox()
media_log_vbox.pack_start(events_panel, True, True, 0)
media_log_panel = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
media_log_panel.set_padding(6, 6, 6, 6)
media_log_panel.add(media_log_vbox)
self.media_log_events_list_view = media_log_events_list_view
# Sequence list
self.sequence_list_view = guicomponents.SequenceListView(
projectaction.sequence_name_edited)
seq_panel = panels.get_sequences_panel(
self.sequence_list_view,
lambda w,e: projectaction.change_edit_sequence(),
lambda w,e: projectaction.add_new_sequence(),
lambda w,e: projectaction.delete_selected_sequence())
# Project info
project_info_panel = projectinfogui.get_project_info_panel()
# Project vbox and panel
project_vbox = gtk.HBox()
project_vbox.pack_start(project_info_panel, False, True, 0)
project_vbox.pack_start(seq_panel, True, True, 0)
project_panel = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
project_panel.set_padding(0, 2, 6, 2)
project_panel.add(project_vbox)
# Notebook
self.notebook = gtk.Notebook()
self.notebook.set_size_request(appconsts.NOTEBOOK_WIDTH, appconsts.TOP_ROW_HEIGHT)
self.notebook.append_page(mm_panel, gtk.Label(_("Media")))
self.notebook.append_page(media_log_panel, gtk.Label(_("Range Log")))
self.notebook.append_page(self.effects_panel, gtk.Label(_("Filters")))
self.notebook.append_page(self.compositors_panel, gtk.Label(_("Compositors")))
self.notebook.append_page(project_panel, gtk.Label(_("Project")))
self.notebook.append_page(render_panel, gtk.Label(_("Render")))
self.notebook.set_tab_pos(gtk.POS_BOTTOM)
# Right notebook, used for Widescreen and Two row layouts
self.right_notebook = gtk.Notebook()
self.right_notebook.set_tab_pos(gtk.POS_BOTTOM)
# Position bar and decorative frame for it
self.pos_bar = PositionBar()
pos_bar_frame = gtk.Frame()
pos_bar_frame.add(self.pos_bar.widget)
pos_bar_frame.set_shadow_type(gtk.SHADOW_ETCHED_IN)
# Positionbar vbox
pos_bar_vbox = gtk.VBox(False, 1)
pos_bar_vbox.pack_start(guiutils.get_pad_label(5, 2), False, True, 0)
pos_bar_vbox.pack_start(pos_bar_frame, False, True, 0)
# Play buttons row
self._create_monitor_row_widgets()
self.player_buttons = glassbuttons.PlayerButtons()
self.player_buttons.widget.set_tooltip_text(_("Prev Frame - Arrow Left\nNext Frame - Arrow Right\nPlay - Space\nStop - Space\nMark In - I\nMark Out - O\nClear Marks\nTo Mark In\nTo Mark Out"))
self.monitor_source.modify_font(pango.FontDescription("sans bold 8"))
player_buttons_row = gtk.HBox(False, 0)
player_buttons_row.pack_start(self.player_buttons.widget, False, True, 0)
player_buttons_row.pack_start(self.monitor_source, True, True, 0)
# Creates monitor switch buttons
self._create_monitor_buttons()
# Switch button box
switch_hbox = gtk.HBox(True, 1)
switch_hbox.pack_start(self.sequence_editor_b, False, False, 0)
switch_hbox.pack_start(self.clip_editor_b, False, False, 0)
# Switch button box V, for centered buttons
switch_vbox = gtk.VBox(False, 1)
switch_vbox.pack_start(guiutils.get_pad_label(5, 2), False, True, 0)
switch_vbox.pack_start(switch_hbox, False, True, 0)
# Switch / pos bar row
self.view_mode_select = guicomponents.get_monitor_view_select_combo(lambda w, e: tlineaction.view_mode_menu_lauched(w, e))
sw_pos_hbox = gtk.HBox(False, 1)
sw_pos_hbox.pack_start(switch_vbox, False, True, 0)
sw_pos_hbox.pack_start(pos_bar_vbox, True, True, 0)
sw_pos_hbox.pack_start(self.view_mode_select.widget, False, False, 0)
# Video display
black_box = gtk.EventBox()
black_box.add(gtk.Label())
bg_color = gtk.gdk.Color(red=0.0, green=0.0, blue=0.0)
black_box.modify_bg(gtk.STATE_NORMAL, bg_color)
self.tline_display = black_box # This can be any GTK+ widget (that is not "windowless"), only its XWindow draw rect
# is used to position and scale SDL overlay that actually displays video.
dnd.connect_video_monitor(self.tline_display)
# Monitor
monitor_vbox = gtk.VBox(False, 1)
monitor_vbox.pack_start(self.tline_display, True, True, 0)
monitor_vbox.pack_start(sw_pos_hbox, False, True, 0)
monitor_vbox.pack_start(player_buttons_row, False, True, 0)
monitor_align = gtk.Alignment(xalign=0.0, yalign=0.0, xscale=1.0, yscale=1.0)
monitor_align.add(monitor_vbox)
monitor_align.set_padding(3, 0, 3, 3)
monitor_frame = gtk.Frame()
monitor_frame.add(monitor_align)
monitor_frame.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
monitor_frame.set_size_request(MONITOR_AREA_WIDTH, appconsts.TOP_ROW_HEIGHT)
# Notebook panel
notebook_vbox = gtk.VBox(False, 1)
notebook_vbox.pack_start(self.notebook, True, True)
# Top row paned
self.top_paned = gtk.HPaned()
self.top_paned.pack1(notebook_vbox, resize=False, shrink=False)
self.top_paned.pack2(monitor_frame, resize=True, shrink=False)
# Top row
self.top_row_hbox = gtk.HBox(False, 0)
self.top_row_hbox.pack_start(self.top_paned, True, True, 0)
self._update_top_row()
# Edit buttons rows
self.edit_buttons_row = self._get_edit_buttons_row()
self.edit_buttons_frame = gtk.Frame()
self.edit_buttons_frame.add(self.edit_buttons_row)
self.edit_buttons_frame.set_shadow_type(gtk.SHADOW_ETCHED_IN)
# Timeline scale
self.tline_scale = tlinewidgets.TimeLineFrameScale(editevent.insert_move_mode_pressed,
updater.mouse_scroll_zoom)
# Timecode display
self.tline_info = gtk.HBox()
info_contents = gtk.Label()
self.tline_info.add(info_contents)
self.tline_info.info_contents = info_contents # this switched and sacved as member of its container
info_h = gtk.HBox()
info_h.pack_start(self.tline_info, False, False, 0)
info_h.pack_start(gtk.Label(), True, True, 0)
info_h.set_size_request(tlinewidgets.COLUMN_WIDTH - 22 - 22,# - 22, # room for 2 menu launch buttons
tlinewidgets.SCALE_HEIGHT)
marker_pixbuf = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "marker.png")
markers_launcher = guicomponents.get_markers_menu_launcher(tlineaction.marker_menu_lauch_pressed, marker_pixbuf)
tracks_launcher_pixbuf = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "track_menu_launch.png")
tracks_launcher = guicomponents.PressLaunch(trackaction.all_tracks_menu_launch_pressed, tracks_launcher_pixbuf)
# Timeline top row
tline_hbox_1 = gtk.HBox()
tline_hbox_1.pack_start(info_h, False, False, 0)
tline_hbox_1.pack_start(tracks_launcher.widget, False, False, 0)
tline_hbox_1.pack_start(markers_launcher.widget, False, False, 0)
tline_hbox_1.pack_start(self.tline_scale.widget, True, True, 0)
# Timeline column
self.tline_column = tlinewidgets.TimeLineColumn(
trackaction.track_active_switch_pressed,
trackaction.track_center_pressed)
# Timeline editpanel
self.tline_canvas = tlinewidgets.TimeLineCanvas(
editevent.tline_canvas_mouse_pressed,
editevent.tline_canvas_mouse_moved,
editevent.tline_canvas_mouse_released,
editevent.tline_canvas_double_click,
updater.mouse_scroll_zoom,
self.tline_cursor_leave,
self.tline_cursor_enter)
dnd.connect_tline(self.tline_canvas.widget, editevent.tline_effect_drop,
editevent.tline_media_drop)
# Timeline middle row
tline_hbox_2 = gtk.HBox()
tline_hbox_2.pack_start(self.tline_column.widget, False, False, 0)
tline_hbox_2.pack_start(self.tline_canvas.widget, True, True, 0)
# Bottom row filler
self.left_corner = guicomponents.TimeLineLeftBottom()
self.left_corner.widget.set_size_request(tlinewidgets.COLUMN_WIDTH, 20)
# Timeline scroller
self.tline_scroller = tlinewidgets.TimeLineScroller(updater.tline_scrolled)
# Timeline bottom row
tline_hbox_3 = gtk.HBox()
tline_hbox_3.pack_start(self.left_corner.widget, False, False, 0)
tline_hbox_3.pack_start(self.tline_scroller, True, True, 0)
# Timeline hbox
tline_vbox = gtk.VBox()
tline_vbox.pack_start(tline_hbox_1, False, False, 0)
tline_vbox.pack_start(tline_hbox_2, True, True, 0)
tline_vbox.pack_start(tline_hbox_3, False, False, 0)
# Timeline box
self.tline_box = gtk.HBox()
self.tline_box.pack_start(tline_vbox, True, True, 0)
# Timeline pane
tline_pane = gtk.VBox(False, 1)
tline_pane.pack_start(self.edit_buttons_frame, False, True, 0)
tline_pane.pack_start(self.tline_box, True, True, 0)
# VPaned top row / timeline
self.app_v_paned = gtk.VPaned()
self.app_v_paned.pack1(self.top_row_hbox, resize=False, shrink=False)
self.app_v_paned.pack2(tline_pane, resize=True, shrink=False)
# Pane
pane = gtk.VBox(False, 1)
pane.pack_start(menu_vbox, False, True, 0)
pane.pack_start(self.app_v_paned, True, True, 0)
# Tooltips
self._add_tool_tips()
# GUI preferences
self._init_gui_to_prefs()
# Viewmenu initial state
self._init_view_menu(ui.get_widget('/MenuBar/ViewMenu'))
# Set pane and show window
self.window.add(pane)
self.window.set_title("Flowblade")
# Maximize if it seems that we exited maximized, else set size
w, h = editorpersistance.prefs.exit_allocation
if w != 0: # non-existing prefs file causes w and h to be 0
if (float(w) / editorstate.SCREEN_WIDTH > 0.95) and (float(h) / editorstate.SCREEN_HEIGHT > 0.95):
self.window.maximize()
print "maximize"
else:
self.window.resize(w, h)
self.window.set_position(gtk.WIN_POS_CENTER)
else:
self.window.set_position(gtk.WIN_POS_CENTER)
# Show window and all of its components
self.window.show_all()
# Set paned positions
self.mm_paned.set_position(editorpersistance.prefs.mm_paned_position)
self.top_paned.set_position(editorpersistance.prefs.top_paned_position)
self.app_v_paned.set_position(editorpersistance.prefs.app_v_paned_position)
def _init_view_menu(self, menu_item):
menu_item.remove_submenu()
menu = gtk.Menu()
mb_menu_item = gtk.MenuItem(_("Middlebar Layout").encode('utf-8'))
mb_menu = gtk.Menu()
tc_left = gtk.RadioMenuItem(None, _("Timecode Left").encode('utf-8'))
tc_left.set_active(True)
tc_left.connect("activate", lambda w: middlebar._show_buttons_TC_LEFT_layout(w))
mb_menu.append(tc_left)
tc_middle = gtk.RadioMenuItem(tc_left, _("Timecode Center").encode('utf-8'))
tc_middle.connect("activate", lambda w: middlebar._show_buttons_TC_MIDDLE_layout(w))
mb_menu.append(tc_middle)
if editorpersistance.prefs.midbar_tc_left == True:
tc_left.set_active(True)
else:
tc_middle.set_active(True)
mb_menu_item.set_submenu(mb_menu)
menu.append(mb_menu_item)
tabs_menu_item = gtk.MenuItem(_("Tabs Position").encode('utf-8'))
tabs_menu = gtk.Menu()
tabs_up = gtk.RadioMenuItem(None, _("Up").encode('utf-8'))
tabs_up.connect("activate", lambda w: self._show_tabs_up(w))
tabs_menu.append(tabs_up)
tabs_down = gtk.RadioMenuItem(tabs_up, _("Down").encode('utf-8'))
tabs_down.connect("activate", lambda w: self._show_tabs_down(w))
if editorpersistance.prefs.tabs_on_top == True:
tabs_up.set_active(True)
else:
tabs_down.set_active(True)
tabs_menu.append(tabs_down)
tabs_menu_item.set_submenu(tabs_menu)
menu.append(tabs_menu_item)
sep = gtk.SeparatorMenuItem()
menu.append(sep)
show_monitor_info_item = gtk.CheckMenuItem(_("Show Monitor Sequence Profile").encode('utf-8'))
show_monitor_info_item.set_active(editorpersistance.prefs.show_sequence_profile)
show_monitor_info_item.connect("toggled", lambda w: middlebar._show_monitor_info_toggled(w))
menu.append(show_monitor_info_item)
show_vu_item = gtk.CheckMenuItem(_("Show Master Volume Meter").encode('utf-8'))
show_vu_item.set_active(editorpersistance.prefs.show_vu_meter)
show_vu_item.connect("toggled", lambda w: self._show_vu_meter(w))
menu.append(show_vu_item)
sep = gtk.SeparatorMenuItem()
menu.append(sep)
interp_menu_item = gtk.MenuItem(_("Monitor Playback Interpolation").encode('utf-8'))
interp_menu = gtk.Menu()
interp_nearest = gtk.RadioMenuItem(None, _("Nearest Neighbour").encode('utf-8'))
interp_nearest.connect("activate", lambda w: monitorevent.set_monitor_playback_interpolation("nearest"))
interp_menu.append(interp_nearest)
interp_bilinear = gtk.RadioMenuItem(interp_nearest, _("Bilinear").encode('utf-8'))
interp_bilinear.connect("activate", lambda w: monitorevent.set_monitor_playback_interpolation("bilinear"))
interp_menu.append(interp_bilinear)
interp_bicubic = gtk.RadioMenuItem(interp_nearest, _("Bicubic").encode('utf-8'))
interp_bicubic.set_active(True)
interp_bicubic.connect("activate", lambda w: monitorevent.set_monitor_playback_interpolation("bicubic"))
interp_menu.append(interp_bicubic)
interp_hyper = gtk.RadioMenuItem(interp_nearest, _("Hyper/Lanczos").encode('utf-8'))
interp_hyper.connect("activate", lambda w: monitorevent.set_monitor_playback_interpolation("hyper"))
interp_menu.append(interp_hyper)
interp_menu_item.set_submenu(interp_menu)
menu.append(interp_menu_item)
sep = gtk.SeparatorMenuItem()
menu.append(sep)
zoom_in_menu_item = gtk.MenuItem(_("Zoom In").encode('utf-8'))
zoom_in_menu_item.connect("activate", lambda w: updater.zoom_in())
menu.append(zoom_in_menu_item)
zoom_out_menu_item = gtk.MenuItem(_("Zoom Out").encode('utf-8'))
zoom_out_menu_item.connect("activate", lambda w: updater.zoom_out())
menu.append(zoom_out_menu_item)
zoom_fit_menu_item = gtk.MenuItem(_("Zoom Fit").encode('utf-8'))
zoom_fit_menu_item.connect("activate", lambda w: updater.zoom_project_length())
menu.append(zoom_fit_menu_item)
menu_item.set_submenu(menu)
def _init_gui_to_prefs(self):
if editorpersistance.prefs.tabs_on_top == True:
self.notebook.set_tab_pos(gtk.POS_TOP)
self.right_notebook.set_tab_pos(gtk.POS_TOP)
else:
self.notebook.set_tab_pos(gtk.POS_BOTTOM)
self.right_notebook.set_tab_pos(gtk.POS_BOTTOM)
def _show_tabs_up(self, widget):
if widget.get_active() == False:
return
self.notebook.set_tab_pos(gtk.POS_TOP)
editorpersistance.prefs.tabs_on_top = True
editorpersistance.save()
def _show_tabs_down(self, widget):
if widget.get_active() == False:
return
self.notebook.set_tab_pos(gtk.POS_BOTTOM)
editorpersistance.prefs.tabs_on_top = False
editorpersistance.save()
def _show_vu_meter(self, widget):
editorpersistance.prefs.show_vu_meter = widget.get_active()
editorpersistance.save()
self._update_top_row(True)
def _update_top_row(self, show_all=False):
if editorpersistance.prefs.show_vu_meter:
if len(self.top_row_hbox) == 1:
self.top_row_hbox.pack_end(audiomonitoring.get_master_meter(), False, False, 0)
else:
if len(self.top_row_hbox) == 2:
meter = self.top_row_hbox.get_children()[1]
self.top_row_hbox.remove(meter)
audiomonitoring.close_master_meter()
if show_all:
self.window.show_all()
def _create_monitor_buttons(self):
# Monitor switch buttons
self.sequence_editor_b = gtk.RadioButton(None) #, _("Timeline"))
self.sequence_editor_b.set_mode(False)
self.sequence_editor_b.set_image(gtk.image_new_from_file(IMG_PATH + "timeline_button.png"))
self.sequence_editor_b.connect("clicked",
lambda w,e: self._monitor_switch_handler(w),
None)
self.sequence_editor_b.set_size_request(100, 25)
self.clip_editor_b = gtk.RadioButton(self.sequence_editor_b)#,_("Clip"))
self.clip_editor_b.set_mode(False)
self.clip_editor_b.set_image(gtk.image_new_from_file(IMG_PATH + "clip_button.png"))
self.clip_editor_b.connect("clicked",
lambda w,e: self._monitor_switch_handler(w),
None)
self.clip_editor_b.set_size_request(100, 25)
def _monitor_switch_handler(self, widget):
# We get two "clicked" events per toggle, send through only the one
# from activated button
if ((self.sequence_editor_b.get_active() == True)
and (widget == self.sequence_editor_b)):
updater.display_sequence_in_monitor()
if ((self.clip_editor_b.get_active() == True)
and (widget == self.clip_editor_b)):
updater.display_clip_in_monitor()
def connect_player(self, mltplayer):
# Buttons
# NOTE: ORDER OF CALLBACKS IS THE SAME AS ORDER OF BUTTONS FROM LEFT TO RIGHT
pressed_callback_funcs = [monitorevent.prev_pressed,
monitorevent.next_pressed,
monitorevent.play_pressed,
monitorevent.stop_pressed,
monitorevent.mark_in_pressed,
monitorevent.mark_out_pressed,
monitorevent.marks_clear_pressed,
monitorevent.to_mark_in_pressed,
monitorevent.to_mark_out_pressed]
self.player_buttons.set_callbacks(pressed_callback_funcs)
# Monitor position bar
self.pos_bar.set_listener(mltplayer.seek_position_normalized)
def _get_edit_buttons_row(self):
modes_pixbufs = [INSERTMOVE_CURSOR, OVERWRITE_CURSOR, ONEROLL_CURSOR, TWOROLL_CURSOR, SLIDE_CURSOR, MULTIMOVE_CURSOR]
middlebar.create_edit_buttons_row_buttons(self, modes_pixbufs)
buttons_row = gtk.HBox(False, 1)
if editorpersistance.prefs.midbar_tc_left == True:
middlebar.fill_with_TC_LEFT_pattern(buttons_row, self)
else:
middlebar.fill_with_TC_MIDDLE_pattern(buttons_row, self)
return buttons_row
def _add_tool_tips(self):
self.big_TC.widget.set_tooltip_text(_("Timeline current frame timecode"))
self.view_mode_select.widget.set_tooltip_text(_("Select view mode: Video/Vectorscope/RGBParade"))
self.tc.widget.set_tooltip_text(_("Monitor Sequence/Media current frame timecode"))
self.monitor_source.set_tooltip_text(_("Current Monitor Sequence/Media name"))
self.pos_bar.widget.set_tooltip_text(_("Monitor Sequence/Media current position"))
self.sequence_editor_b.set_tooltip_text(_("Display Current Sequence on Timeline"))
self.clip_editor_b.set_tooltip_text(_("Display Monitor Clip"))
def handle_over_move_mode_button_press(self):
editevent.overwrite_move_mode_pressed()
self.set_cursor_to_mode()
def handle_insert_move_mode_button_press(self):
editevent.insert_move_mode_pressed()
self.set_cursor_to_mode()
def handle_one_roll_mode_button_press(self):
editevent.oneroll_trim_no_edit_init()
self.set_cursor_to_mode()
def handle_two_roll_mode_button_press(self):
editevent.tworoll_trim_no_edit_init()
self.set_cursor_to_mode()
def handle_slide_mode_button_press(self):
editevent.slide_trim_no_edit_init()
self.set_cursor_to_mode()
def handle_multi_mode_button_press(self):
editevent.multi_mode_pressed()
self.set_cursor_to_mode()
def mode_selector_pressed(self, selector, event):
guicomponents.get_mode_selector_popup_menu(selector, event, self.mode_selector_item_activated)
def mode_selector_item_activated(self, selector, mode):
if mode == 0:
self.handle_insert_move_mode_button_press()
if mode == 1:
self.handle_over_move_mode_button_press()
if mode == 2:
self.handle_one_roll_mode_button_press()
if mode == 3:
self.handle_two_roll_mode_button_press()
if mode == 4:
self.handle_slide_mode_button_press()
if mode == 5:
self.handle_multi_mode_button_press()
self.set_cursor_to_mode()
self.set_mode_selector_to_mode()
def set_cursor_to_mode(self):
if editorstate.cursor_on_tline == True:
self.set_tline_cursor(editorstate.EDIT_MODE())
else:
gdk_window = gui.tline_display.get_parent_window();
gdk_window.set_cursor(gtk.gdk.Cursor(gtk.gdk.LEFT_PTR))
def set_tline_cursor(self, mode):
display = gtk.gdk.display_get_default()
gdk_window = gui.tline_display.get_parent_window()
if mode == editorstate.INSERT_MOVE:
cursor = gtk.gdk.Cursor(display, INSERTMOVE_CURSOR, 0, 0)
elif mode == editorstate.OVERWRITE_MOVE:
cursor = gtk.gdk.Cursor(display, OVERWRITE_CURSOR, 6, 15)
elif mode == editorstate.TWO_ROLL_TRIM:
cursor = gtk.gdk.Cursor(display, TWOROLL_CURSOR, 11, 9)
elif mode == editorstate.TWO_ROLL_TRIM_NO_EDIT:
cursor = gtk.gdk.Cursor(display, TWOROLL_NO_EDIT_CURSOR, 11, 9)
elif mode == editorstate.ONE_ROLL_TRIM:
cursor = gtk.gdk.Cursor(display, ONEROLL_CURSOR, 9, 9)
elif mode == editorstate.ONE_ROLL_TRIM_NO_EDIT:
cursor = gtk.gdk.Cursor(display, ONEROLL_NO_EDIT_CURSOR, 9, 9)
elif mode == editorstate.SLIDE_TRIM:
cursor = gtk.gdk.Cursor(display, SLIDE_CURSOR, 9, 9)
elif mode == editorstate.SLIDE_TRIM_NO_EDIT:
cursor = gtk.gdk.Cursor(display, SLIDE_NO_EDIT_CURSOR, 9, 9)
elif mode == editorstate.SELECT_PARENT_CLIP:
cursor = gtk.gdk.Cursor(gtk.gdk.TCROSS)
elif mode == editorstate.MULTI_MOVE:
cursor = gtk.gdk.Cursor(display, MULTIMOVE_CURSOR, 4, 8)
else:
cursor = gtk.gdk.Cursor(gtk.gdk.LEFT_PTR)
gdk_window.set_cursor(cursor)
def set_mode_selector_to_mode(self):
if editorstate.EDIT_MODE() == editorstate.INSERT_MOVE:
self.modes_selector.set_pixbuf(0)
elif editorstate.EDIT_MODE() == editorstate.OVERWRITE_MOVE:
self.modes_selector.set_pixbuf(1)
elif editorstate.EDIT_MODE() == editorstate.ONE_ROLL_TRIM:
self.modes_selector.set_pixbuf(2)
elif editorstate.EDIT_MODE() == editorstate.ONE_ROLL_TRIM_NO_EDIT:
self.modes_selector.set_pixbuf(2)
elif editorstate.EDIT_MODE() == editorstate.TWO_ROLL_TRIM:
self.modes_selector.set_pixbuf(3)
elif editorstate.EDIT_MODE() == editorstate.TWO_ROLL_TRIM_NO_EDIT:
self.modes_selector.set_pixbuf(3)
elif editorstate.EDIT_MODE() == editorstate.SLIDE_TRIM:
self.modes_selector.set_pixbuf(4)
elif editorstate.EDIT_MODE() == editorstate.SLIDE_TRIM_NO_EDIT:
self.modes_selector.set_pixbuf(4)
elif editorstate.EDIT_MODE() == editorstate.MULTI_MOVE:
self.modes_selector.set_pixbuf(5)
def tline_cursor_leave(self, event):
editorstate.cursor_on_tline = False
self.set_cursor_to_mode()
if event.state & gtk.gdk.BUTTON1_MASK:
if editorstate.current_is_move_mode():
tlineaction.mouse_dragged_out(event)
def tline_cursor_enter(self, event):
editorstate.cursor_on_tline = True
self.set_cursor_to_mode()
def top_paned_resized(self, w, req):
print self.app_v_paned.get_position()
print self.top_paned.get_position()
print self.mm_paned.get_position()
def _create_monitor_row_widgets(self):
self.tc = guicomponents.MonitorTCDisplay()
self.monitor_source = gtk.Label("sequence1")
self.monitor_source.set_ellipsize(pango.ELLIPSIZE_END)
def _this_is_not_used():
print "THIS WAS USED!!!!!"
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module checks environment for available codecs and formats.
"""
import gobject
import mlt
import dialogutils
import editorstate
import gui
acodecs = None
vcodecs = None
formats = None
services = None
transitions = None
environment_detection_success = False
def check_available_features(repo):
try:
print "Detecting environment..."
global acodecs
global vcodecs
global formats
global services
global transitions
global environment_detection_success
acodecs = []
vcodecs = []
formats = []
services = {}
transitions = {}
# video codecs
cv = mlt.Consumer(mlt.Profile(), "avformat")
cv.set('vcodec', 'list')
cv.start()
codecs = mlt.Properties(cv.get_data('vcodec'))
for i in range(0, codecs.count()):
vcodecs.append(codecs.get(i))
# audio codecs
ca = mlt.Consumer(mlt.Profile(), "avformat")
ca.set('acodec', 'list')
ca.start()
codecs = mlt.Properties(ca.get_data('acodec'))
for i in range(0, codecs.count()):
acodecs.append(codecs.get(i))
# formats
cf = mlt.Consumer(mlt.Profile(), "avformat")
cf.set('f', 'list')
cf.start()
codecs = mlt.Properties(cf.get_data('f'))
for i in range(0, codecs.count()):
formats.append(codecs.get(i))
# filters
envservices = mlt.Repository.filters(repo)
for i in range(mlt.Properties.count(envservices)):
services[mlt.Properties.get_name(envservices, i)] = True
# transitions
envtransitions = mlt.Repository.transitions(repo)
for i in range(mlt.Properties.count(envtransitions)):
transitions[mlt.Properties.get_name(envtransitions, i)] = True
print "MLT detection succeeded, " + str(len(formats)) + " formats, " \
+ str(len(vcodecs)) + " video codecs and " + str(len(acodecs)) + " audio codecs found."
print str(len(services)) + " MLT services found."
environment_detection_success = True
except:
print "Environment detection failed, environment unknown."
gobject.timeout_add(2000, _show_failed_environment_info)
def render_profile_supported(frmt, vcodec, acodec):
if environment_detection_success == False:
return (True, "")
if acodec in acodecs or acodec == None: # some encoding options do not specify audio codecs
if vcodec in vcodecs or vcodec == None: # some encoding options do not specify video codecs
if frmt in formats or frmt == None: # some encoding options do not specify formats
return (True, "")
else:
err_msg = "format " + frmt
else:
err_msg = "video codec " + vcodec
else:
err_msg = "audio codec " + acodec
return (False, err_msg)
def _show_failed_environment_info():
primary_txt = "Environment detection failed!"
secondary_txt = "You will probably be presented with filters, transitions\nand rendering options that are not available on your system." + \
"\n---\nYou may experience sudden crashes when adding filters or\nattempting rendering." + \
"\n---\nYour MLT Version is: "+ editorstate.mlt_version + "\n" + \
"Only report this as a bug if the MLT version above is >= 0.7.6."
dialogutils.info_message(primary_txt, secondary_txt, gui.editor_window.window)
return False
| Python |
#!/usr/bin/env python
import sys
import os
modules_path = os.path.dirname(os.path.abspath(sys.argv[0])).rstrip("/launch")
sys.path.insert(0, modules_path)
sys.path.insert(0, modules_path + "/vieweditor")
sys.path.insert(0, modules_path + "/tools")
import batchrendering
batchrendering.main(modules_path)
| Python |
#!/usr/bin/env python
import sys
import os
modules_path = os.path.dirname(os.path.abspath(sys.argv[0])).rstrip("/launch")
sys.path.insert(0, modules_path)
sys.path.insert(0, modules_path + "/vieweditor")
sys.path.insert(0, modules_path + "/tools")
import medialinker
medialinker.main(modules_path)
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module contains functions to build generic dialogs.
"""
import gobject
import pygtk
pygtk.require('2.0');
import gtk
import guiutils
def dialog_destroy(dialog, response):
dialog.destroy()
def default_behaviour(dialog):
dialog.set_default_response(gtk.RESPONSE_OK)
dialog.set_has_separator(False)
dialog.set_resizable(False)
def panel_ok_dialog(title, panel):
dialog = gtk.Dialog(title, None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
( _("OK").encode('utf-8'), gtk.RESPONSE_OK))
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(6, 24, 12, 12)
alignment.add(panel)
dialog.vbox.pack_start(alignment, True, True, 0)
default_behaviour(dialog)
dialog.connect('response', dialog_destroy)
dialog.show_all()
def info_message(primary_txt, secondary_txt, parent_window):
warning_message(primary_txt, secondary_txt, parent_window, is_info=True)
def warning_message(primary_txt, secondary_txt, parent_window, is_info=False):
warning_message_with_callback(primary_txt, secondary_txt, parent_window, is_info, dialog_destroy)
def warning_message_with_callback(primary_txt, secondary_txt, parent_window, is_info, callback):
content = get_warning_message_dialog_panel(primary_txt, secondary_txt, is_info)
dialog = gtk.Dialog("",
parent_window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
( _("OK").encode('utf-8'), gtk.RESPONSE_ACCEPT))
dialog.vbox.pack_start(content, True, True, 0)
dialog.set_has_separator(False)
dialog.set_resizable(False)
dialog.connect('response', callback)
dialog.show_all()
def warning_confirmation(callback, primary_txt, secondary_txt, parent_window, data=None, is_info=False):
content = get_warning_message_dialog_panel(primary_txt, secondary_txt, is_info)
align = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
align.set_padding(0, 12, 0, 0)
align.add(content)
dialog = gtk.Dialog("",
parent_window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(_("Cancel").encode('utf-8'), gtk.RESPONSE_REJECT,
_("OK").encode('utf-8'), gtk.RESPONSE_ACCEPT))
dialog.vbox.pack_start(align, True, True, 0)
dialog.set_has_separator(False)
dialog.set_resizable(False)
if data == None:
dialog.connect('response', callback)
else:
dialog.connect('response', callback, data)
print "eeee"
dialog.show_all()
def get_warning_message_dialog_panel(primary_txt, secondary_txt, is_info=False, alternative_icon=None):
if is_info == True:
icon = gtk.STOCK_DIALOG_INFO
else:
icon = gtk.STOCK_DIALOG_WARNING
if alternative_icon != None:
icon = alternative_icon
warning_icon = gtk.image_new_from_stock(icon, gtk.ICON_SIZE_DIALOG)
icon_box = gtk.VBox(False, 2)
icon_box.pack_start(warning_icon, False, False, 0)
icon_box.pack_start(gtk.Label(), True, True, 0)
p_label = guiutils.bold_label(primary_txt)
s_label = gtk.Label(secondary_txt)
s_label.set_use_markup(True)
texts_pad = gtk.Label()
texts_pad.set_size_request(12,12)
pbox = gtk.HBox(False, 1)
pbox.pack_start(p_label, False, False, 0)
pbox.pack_start(gtk.Label(), True, True, 0)
sbox = gtk.HBox(False, 1)
sbox.pack_start(s_label, False, False, 0)
sbox.pack_start(gtk.Label(), True, True, 0)
text_box = gtk.VBox(False, 0)
text_box.pack_start(pbox, False, False, 0)
text_box.pack_start(texts_pad, False, False, 0)
text_box.pack_start(sbox, False, False, 0)
text_box.pack_start(gtk.Label(), True, True, 0)
hbox = gtk.HBox(False, 12)
hbox.pack_start(icon_box, False, False, 0)
hbox.pack_start(text_box, True, True, 0)
align = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
align.set_padding(12, 0, 12, 12)
align.add(hbox)
return align
def get_single_line_text_input_dialog(chars, label_width,title, ok_button_text,
label, default_text):
dialog = gtk.Dialog(title, None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(_("Cancel").encode('utf-8'), gtk.RESPONSE_REJECT,
ok_button_text, gtk.RESPONSE_OK))
entry = gtk.Entry(30)
entry.set_width_chars(30)
entry.set_text(default_text)
entry.set_activates_default(True)
entry_row = guiutils.get_two_column_box(gtk.Label(label),
entry,
180)
vbox = gtk.VBox(False, 2)
vbox.pack_start(entry_row, False, False, 0)
vbox.pack_start(guiutils.get_pad_label(12, 12), False, False, 0)
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(6, 24, 24, 24)
alignment.add(vbox)
dialog.vbox.pack_start(alignment, True, True, 0)
default_behaviour(dialog)
dialog.set_default_response(gtk.RESPONSE_ACCEPT)
return (dialog, entry)
def get_default_alignment(panel):
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(6, 24, 24, 24)
alignment.add(panel)
return alignment
def get_alignment2(panel):
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(6, 24, 12, 12)
alignment.add(panel)
return alignment
# ------------------------------------------------------------------ delayed window destroying
def delay_destroy_window(window, delay):
gobject.timeout_add(int(delay * 1000), _window_destroy_event, window)
def _window_destroy_event(window):
window.destroy()
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
import appconsts
from editorstate import current_sequence
# Syncing clips
#
# Sync is created by selecting a parent clip for the child clip. Parent clips
# must be on track V1.
#
# Setting sync means calculating and saving the position difference between where first frames of clips
# would be on the timeline.
#
# After every edit sync states of all child clips is calculated, and it
# gets displayd to the user in the next timeline redraw using red, green and gray colors
# Maps clip -> track
sync_children = {}
# ----------------------------------------- sync display updating
def clip_added_to_timeline(clip, track):
if clip.sync_data != None:
sync_children[clip] = track
def clip_removed_from_timeline(clip):
try:
sync_children.pop(clip)
except KeyError:
pass
def clip_sync_cleared(clip):
# This and the method above are called for different purposes, so we'll
# keep them separate even though they do the same thing. (???)
try:
sync_children.pop(clip)
except KeyError:
pass
def sequence_changed(new_sequence):
global sync_children
sync_children = {}
for track in new_sequence.tracks:
for clip in track.clips:
clip_added_to_timeline(clip, track)
calculate_and_set_child_clip_sync_states()
def calculate_and_set_child_clip_sync_states():
parent_track = current_sequence().first_video_track()
for child_clip, track in sync_children.iteritems():
child_index = track.clips.index(child_clip)
child_clip_start = track.clip_start(child_index) - child_clip.clip_in
#print child_clip.id
parent_clip = child_clip.sync_data.master_clip
try:
parent_index = parent_track.clips.index(parent_clip)
except:
child_clip.sync_data.sync_state = appconsts.SYNC_PARENT_GONE
continue
parent_clip_start = parent_track.clip_start(parent_index) - parent_clip.clip_in
pos_offset = child_clip_start - parent_clip_start
if pos_offset == child_clip.sync_data.pos_offset:
child_clip.sync_data.sync_state = appconsts.SYNC_CORRECT
else:
child_clip.sync_data.sync_state = appconsts.SYNC_OFF
child_clip.sync_diff = pos_offset - child_clip.sync_data.pos_offset
def get_resync_data_list():
# Returns list of tuples with data needed to do resync
# Return tuples (clip, track, index, pos_off)
resync_data = []
parent_track = current_sequence().first_video_track()
for child_clip, track in sync_children.iteritems():
child_index = track.clips.index(child_clip)
child_clip_start = track.clip_start(child_index) - child_clip.clip_in
parent_clip = child_clip.sync_data.master_clip
try:
parent_index = parent_track.clips.index(parent_clip)
except:
# Parent clip no longer awailable
continue
parent_clip_start = parent_track.clip_start(parent_index) - parent_clip.clip_in
pos_offset = child_clip_start - parent_clip_start
resync_data.append((child_clip, track, child_index, pos_offset))
return resync_data
def get_resync_data_list_for_clip_list(clips_list):
# Input is list of (clip, track) tuples
# Returns list of tuples with data needed to do resync
# Return tuples (clip, track, index, pos_off)
resync_data = []
parent_track = current_sequence().first_video_track()
for clip_track_tuple in clips_list:
child_clip, track = clip_track_tuple
child_index = track.clips.index(child_clip)
child_clip_start = track.clip_start(child_index) - child_clip.clip_in
parent_clip = child_clip.sync_data.master_clip
try:
parent_index = parent_track.clips.index(parent_clip)
except:
# Parent clip no longer awailable
continue
parent_clip_start = parent_track.clip_start(parent_index) - parent_clip.clip_in
pos_offset = child_clip_start - parent_clip_start
resync_data.append((child_clip, track, child_index, pos_offset))
return resync_data
def print_sync_children():
for child_clip, track in sync_children.iteritems():
print child_clip.id
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module handles drag and drop.
"""
import pygtk
pygtk.require('2.0');
import gtk
import editorstate
import gui
import respaths
# GUI consts
MEDIA_ICON_WIDTH = 20
MEDIA_ICON_HEIGHT = 15
MEDIA_FILES_DND_TARGET = ('media_file', gtk.TARGET_SAME_APP, 0)
EFFECTS_DND_TARGET = ('effect', gtk.TARGET_SAME_APP, 0)
CLIPS_DND_TARGET = ('clip', gtk.TARGET_SAME_APP, 0)
RANGE_DND_TARGET = ('range', gtk.TARGET_SAME_APP, 0)
STRING_DATA_BITS = 8
# Holds data during drag
drag_data = None
# Drag icons
clip_icon = None
empty_icon = None
# Callback functions
add_current_effect = None
display_monitor_media_file = None
range_log_items_tline_drop = None
range_log_items_log_drop = None
def init():
global clip_icon, empty_icon
clip_icon = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "clip_dnd.png")
empty_icon = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "empty.png")
# ----------------------------------------------- set gui components as drag sources and destinations
def connect_media_files_object_widget(widget):
widget.drag_source_set(gtk.gdk.BUTTON1_MASK,
[MEDIA_FILES_DND_TARGET],
gtk.gdk.ACTION_COPY)
widget.connect_after('drag_begin', _media_files_drag_begin)
widget.connect("drag_data_get", _media_files_drag_data_get)
def connect_media_files_object_cairo_widget(widget):
widget.drag_source_set(gtk.gdk.BUTTON1_MASK,
[MEDIA_FILES_DND_TARGET],
gtk.gdk.ACTION_COPY)
widget.connect_after('drag_begin', _media_files_drag_begin)
widget.connect("drag_data_get", _media_files_drag_data_get)
def connect_bin_tree_view(treeview, move_files_to_bin_func):
treeview.enable_model_drag_dest([MEDIA_FILES_DND_TARGET],
gtk.gdk.ACTION_DEFAULT)
treeview.connect("drag_data_received", _bin_drag_data_received, move_files_to_bin_func)
def connect_effects_select_tree_view(tree_view):
tree_view.enable_model_drag_source(gtk.gdk.BUTTON1_MASK,
[EFFECTS_DND_TARGET],
gtk.gdk.ACTION_COPY)
tree_view.connect_after('drag_begin', _effects_drag_begin)
tree_view.connect("drag_data_get", _effects_drag_data_get)
def connect_video_monitor(widget):
widget.drag_dest_set(gtk.DEST_DEFAULT_MOTION | gtk.DEST_DEFAULT_DROP,
[MEDIA_FILES_DND_TARGET],
gtk.gdk.ACTION_COPY)
widget.connect("drag_drop", _on_monitor_drop)
widget.drag_source_set(gtk.gdk.BUTTON1_MASK,
[MEDIA_FILES_DND_TARGET],
gtk.gdk.ACTION_COPY)
widget.connect_after('drag_begin', _monitor_media_drag_begin)
widget.connect("drag_data_get", _monitor_media_drag_data_get)
def connect_stack_treeview(widget):
widget.drag_dest_set(gtk.DEST_DEFAULT_MOTION | gtk.DEST_DEFAULT_DROP,
[EFFECTS_DND_TARGET],
gtk.gdk.ACTION_COPY)
widget.connect("drag_drop", _on_effect_stack_drop)
def connect_tline(widget, do_effect_drop_func, do_media_drop_func):
widget.drag_dest_set(gtk.DEST_DEFAULT_MOTION | gtk.DEST_DEFAULT_DROP,
[MEDIA_FILES_DND_TARGET, EFFECTS_DND_TARGET, CLIPS_DND_TARGET],
gtk.gdk.ACTION_COPY)
widget.connect("drag_drop", _on_tline_drop, do_effect_drop_func, do_media_drop_func)
def connect_range_log(treeview):
treeview.drag_source_set(gtk.gdk.BUTTON1_MASK,
[CLIPS_DND_TARGET],
gtk.gdk.ACTION_COPY)
treeview.connect_after('drag_begin', _range_log_drag_begin)
treeview.connect("drag_data_get", _range_log_drag_data_get)
treeview.drag_dest_set(gtk.DEST_DEFAULT_MOTION | gtk.DEST_DEFAULT_DROP,
[RANGE_DND_TARGET],
gtk.gdk.ACTION_COPY)
treeview.connect("drag_drop", _on_range_drop)
def start_tline_clips_out_drag(event, clips, widget):
global drag_data
drag_data = clips
context = widget.drag_begin([RANGE_DND_TARGET], gtk.gdk.ACTION_COPY, 1, event)
if context == None: # if something outside of the application is clicked we'll end here and cannot create a context
return
context.set_icon_pixbuf(clip_icon, 30, 15)
# ------------------------------------------------- handlers for drag events
def _media_files_drag_begin(treeview, context):
_save_media_panel_selection()
context.set_icon_pixbuf(clip_icon, 30, 15)
def _media_files_drag_data_get(widget, context, selection, target_id, timestamp):
_save_media_panel_selection()
def _monitor_media_drag_begin(widget, context):
success = _save_monitor_media()
if success:
context.set_icon_pixbuf(clip_icon, 30, 15)
else:
context.set_icon_pixbuf(empty_icon, 30, 15)
def _monitor_media_drag_data_get(widget, context, selection, target_id, timestamp):
pass
#context.set_icon_pixbuf(clip_icon, 30, 15)
def _range_log_drag_begin(widget, context):
context.set_icon_pixbuf(clip_icon, 30, 15)
def _range_log_drag_data_get(treeview, context, selection, target_id, timestamp):
_save_treeview_selection(treeview)
def _effects_drag_begin(widget, context):
pass
def _effects_drag_data_get(treeview, context, selection, target_id, timestamp):
_save_treeview_selection(treeview)
def _on_monitor_drop(widget, context, x, y, timestamp):
context.finish(True, False, timestamp)
media_file = drag_data[0].media_file
display_monitor_media_file(media_file)
gui.pos_bar.widget.grab_focus()
def _on_effect_stack_drop(widget, context, x, y, timestamp):
context.finish(True, False, timestamp)
add_current_effect()
def _bin_drag_data_received(treeview, context, x, y, selection, info, etime, move_files_to_bin_func):
bin_path, drop_pos = treeview.get_dest_row_at_pos(x, y)
moved_rows = []
for media_object in drag_data:
moved_rows.append(media_object.bin_index)
move_files_to_bin_func(max(bin_path), moved_rows)
def _save_treeview_selection(treeview):
treeselection = treeview.get_selection()
(model, rows) = treeselection.get_selected_rows()
global drag_data
drag_data = rows
def _save_media_panel_selection():
global drag_data
drag_data = gui.media_list_view.get_selected_media_objects()
def _save_monitor_media():
media_file = editorstate.MONITOR_MEDIA_FILE()
global drag_data
drag_data = media_file
if media_file == None:
return False
return True
def _on_tline_drop(widget, context, x, y, timestamp, do_effect_drop_func, do_media_drop_func):
if context.get_source_widget() == gui.effect_select_list_view.treeview:
do_effect_drop_func(x, y)
gui.tline_canvas.widget.grab_focus()
elif hasattr(context.get_source_widget(), "dnd_media_widget_attr") or hasattr(context.get_source_widget(), "dnd_media_widget_attr"):
media_file = drag_data[0].media_file
do_media_drop_func(media_file, x, y)
gui.tline_canvas.widget.grab_focus()
elif context.get_source_widget() == gui.tline_display:
if drag_data != None:
do_media_drop_func(drag_data, x, y, True)
gui.tline_canvas.widget.grab_focus()
else:
print "monitor_drop fail"
elif context.get_source_widget() == gui.editor_window.media_log_events_list_view.treeview:
range_log_items_tline_drop(drag_data, x, y)
else:
print "_on_tline_drop failed to do anything"
context.finish(True, False, timestamp)
def _on_range_drop(widget, context, x, y, timestamp):
range_log_items_log_drop(drag_data)
context.finish(True, False, timestamp)
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module contains CairoDrawableArea widget. You can draw onto it using
Cairo, and listen to its mouse and keyboard events.
"""
import pygtk
pygtk.require('2.0');
import gtk
from gtk import gdk
class CairoDrawableArea(gtk.Widget):
"""
A widget for creating custom components using Cairo canvas.
"""
__gsignals__ = { 'realize': 'override',
'expose-event' : 'override',
'size-allocate': 'override',
'size-request': 'override',}
def __init__(self, pref_width, pref_height, func_draw, use_widget_bg=False):
# Init widget.
gtk.Widget.__init__(self)
# Preferred size. Parant container has an effect on actual size.
self._pref_width = pref_width
self._pref_height = pref_height
self._use_widget_bg = use_widget_bg
# Set callback funcs
# Draw, must be provided
self._draw_func = func_draw
# Mouse events, set default noops
self.press_func = self._press
self.release_func = self._release
self.motion_notify_func = self._motion_notify
self.leave_notify_func = self._leave
self.enter_notify_func = self._enter
self.mouse_scroll_func = None
# Flag for grabbing focus
self.grab_focus_on_press = True
def do_realize(self):
# Set an internal flag telling that we're realized
self.set_flags(self.flags() | gtk.REALIZED)
# Create GDK window
self.window = gdk.Window(self.get_parent_window(),
width=self.allocation.width,
height=self.allocation.height,
window_type=gdk.WINDOW_CHILD,
wclass=gdk.INPUT_OUTPUT,
event_mask=self.get_events()
| gdk.EXPOSURE_MASK
| gdk.BUTTON_PRESS_MASK
| gdk.BUTTON_RELEASE_MASK
| gdk.BUTTON_MOTION_MASK
| gdk.POINTER_MOTION_HINT_MASK
| gdk.ENTER_NOTIFY_MASK
| gdk.LEAVE_NOTIFY_MASK
| gdk.KEY_PRESS_MASK
| gdk.SCROLL_MASK)
# Connect motion notify event
self.connect('motion_notify_event', self._motion_notify_event)
# Connect mouse scroll event
self.connect("scroll-event", self._mouse_scroll_event)
# Make widget capable of grabbing focus
self.set_property("can-focus", True)
# Check that cairo context can be created
if not hasattr(self.window, "cairo_create"):
print "no cairo"
raise SystemExit
# GTK+ stores the widget that owns a gtk.gdk.Window as user data on it.
# Custom widgets should do this too
self.window.set_user_data(self)
# Attach style
self.style.attach(self.window)
# Set background color
if(self._use_widget_bg):
self.style.set_background(self.window, gtk.STATE_NORMAL)
# Set size and place
self.window.move_resize(*self.allocation)
def set_pref_size(self, pref_width, pref_height):
self._pref_width = pref_width
self._pref_height = pref_height
# Gtk+ callback to ask widgets preferred size
def do_size_request(self, requisition):
requisition.width = self._pref_width
requisition.height = self._pref_height
# Gtk+ callback to tell widget its allocated size
def do_size_allocate(self, allocation):
# This is called by when widget size is known
# new size in tuple allocation
self.allocation = allocation
if self.flags() & gtk.REALIZED:
self.window.move_resize(*allocation)
# Noop funcs for unhandled events
def _press(self, event):
pass
def _release(self, event):
pass
def _motion_notify(self, x, y, state):
pass
def _enter(self, event):
pass
def _leave(self, event):
pass
# Event handlers
# Expose event callback
# Create cairo context and pass it on for custom widget drawing.
def do_expose_event(self, event):
self.chain(event)
try:
cr = self.window.cairo_create()
except AttributeError:
print "Cairo create failed"
raise SystemExit
return self._draw_func(event, cr, self.allocation)
# Mouse press / release events
def do_button_press_event(self, event):
if self.grab_focus_on_press:
self.grab_focus()
self.press_func(event)
return True
def do_button_release_event(self, event):
self.release_func(event)
return True
def _mouse_scroll_event(self, widget, event):
if self.mouse_scroll_func == None:
return
self.mouse_scroll_func(event)
# Mouse drag event
def _motion_notify_event(self, widget, event):
if event.is_hint:
x, y, state = event.window.get_pointer()
else:
x = event.x
y = event.y
state = event.state
self.motion_notify_func(x, y, state)
# Enter / leave events
def do_enter_notify_event(self, event):
self.enter_notify_func(event)
def do_leave_notify_event(self, event):
self.leave_notify_func(event)
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2013 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
import pygtk
pygtk.require('2.0');
import gtk
import pango
from editorstate import PROJECT
import guicomponents
import guiutils
import utils
widgets = utils.EmptyClass()
def get_project_info_panel():
project_name_label = gtk.Label(PROJECT().name)
name_row = guiutils.get_left_justified_box([project_name_label])
name_panel = guiutils.get_named_frame(_("Name"), name_row, 4)
profile = PROJECT().profile
desc_label = gtk.Label(profile.description())
info_box = guicomponents.get_profile_info_small_box(profile)
vbox = gtk.VBox()
vbox.pack_start(guiutils.get_left_justified_box([desc_label]), False, True, 0)
vbox.pack_start(info_box, False, True, 0)
profile_panel = guiutils.get_named_frame(_("Profile"), vbox, 4)
events_list = ProjectEventListView()
events_list.set_size_request(270, 300)
events_list.fill_data_model()
events_panel = guiutils.get_named_frame(_("Project Events"), events_list, 4)
project_info_vbox = gtk.VBox()
project_info_vbox.pack_start(name_panel, False, True, 0)
project_info_vbox.pack_start(profile_panel, False, True, 0)
project_info_vbox.pack_start(events_panel, True, True, 0)
align = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
align.set_padding(0, 0, 0, 0)
align.add(project_info_vbox)
widgets.project_name_label = project_name_label
widgets.desc_label = desc_label
widgets.info_box = info_box
widgets.events_list = events_list
return align
def update_project_info():
profile = PROJECT().profile
widgets.project_name_label.set_text(PROJECT().name)
widgets.desc_label.set_text(profile.description())
profile_info_text = guicomponents.get_profile_info_text(profile)
widgets.info_box.get_children()[0].set_text(profile_info_text)
widgets.events_list.fill_data_model()
class ProjectEventListView(gtk.VBox):
def __init__(self):
gtk.VBox.__init__(self)
# Datamodel: text, text, text
self.storemodel = gtk.ListStore(str, str, str)
# Scroll container
self.scroll = gtk.ScrolledWindow()
self.scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.scroll.set_shadow_type(gtk.SHADOW_ETCHED_IN)
# View
self.treeview = gtk.TreeView(self.storemodel)
self.treeview.set_property("rules_hint", True)
self.treeview.set_headers_visible(True)
tree_sel = self.treeview.get_selection()
tree_sel.set_mode(gtk.SELECTION_SINGLE)
# Column views
self.text_col_1 = gtk.TreeViewColumn("text1")
self.text_col_1.set_title(_("Date"))
self.text_col_2 = gtk.TreeViewColumn("text2")
self.text_col_2.set_title(_("Event"))
self.text_col_3 = gtk.TreeViewColumn("text3")
self.text_col_3.set_title(_("Path"))
# Cell renderers
self.text_rend_1 = gtk.CellRendererText()
self.text_rend_1.set_property("ellipsize", pango.ELLIPSIZE_END)
self.text_rend_2 = gtk.CellRendererText()
self.text_rend_2.set_property("yalign", 0.0)
self.text_rend_3 = gtk.CellRendererText()
self.text_rend_3.set_property("yalign", 0.0)
# Build column views
self.text_col_1.set_expand(True)
self.text_col_1.set_spacing(5)
self.text_col_1.set_sizing(gtk.TREE_VIEW_COLUMN_GROW_ONLY)
self.text_col_1.set_min_width(150)
self.text_col_1.pack_start(self.text_rend_1)
self.text_col_1.add_attribute(self.text_rend_1, "text", 0)
self.text_col_2.set_expand(True)
self.text_col_2.pack_start(self.text_rend_2)
self.text_col_2.add_attribute(self.text_rend_2, "text", 1)
self.text_col_3.set_expand(True)
self.text_col_3.pack_start(self.text_rend_3)
self.text_col_3.add_attribute(self.text_rend_3, "text", 2)
# Add column views to view
self.treeview.append_column(self.text_col_1)
self.treeview.append_column(self.text_col_2)
self.treeview.append_column(self.text_col_3)
# Build widget graph and display
self.scroll.add(self.treeview)
self.pack_start(self.scroll)
self.scroll.show_all()
def fill_data_model(self):
self.storemodel.clear()
for e in PROJECT().events:
t = e.get_date_str()
desc, path = e.get_desc_and_path()
row_data = [t, desc, path]
self.storemodel.append(row_data)
self.scroll.queue_draw()
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module contains GUI update routines.
"""
import pygtk
pygtk.require('2.0');
import gtk
import appconsts
import clipeffectseditor
import compositeeditor
import gui
import editorstate
from editorstate import current_sequence
from editorstate import MONITOR_MEDIA_FILE
from editorstate import PLAYER
from editorstate import PROJECT
from editorstate import timeline_visible
import editorpersistance
import monitorevent
import utils
import respaths
import tlinewidgets
page_size = 99.0 # gtk.Adjustment.get_page_size() wasn't there
# (wft?) so use this to have page size
# Scale constants
PIX_PER_FRAME_MAX = 20.0
PIX_PER_FRAME_MIN = 0.001
SCALE_MULTIPLIER = 0.66
# Trim edit loop playback
TRIM_EDIT_PRE_ROLL = 25
TRIM_EDIT_POST_ROLL = 20
# Current limit for full view scale
pix_per_frame_full_view = 0.2
# Icons
IMG_PATH = None
play_icon = None
play_loop_icon = None
next_icon = None
next_trim_icon = None
prev_icon = None
prev_trim_icon = None
stop_icon = None
stop_trim_icon = None
# Callback func to set default editmode, set from outside of the module.
set_clip_edit_mode_callback = None
# Timeline position is saved when clip is displayed
saved_timeline_pos = -1
last_clicked_media_row = -1
# This needs to blocked for first and last window state events
player_refresh_enabled = False
# This needs to be blocked when timeline is displayed as result
# of Append/Inset... from monitor to get correct results
save_monitor_frame = False
# ---------------------------------- init
def load_icons():
"""
These icons are switched when changing between trim and move modes
"""
global play_icon, play_loop_icon, next_icon, next_trim_icon, \
prev_icon, prev_trim_icon, stop_icon, stop_trim_icon
play_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "play_2_s.png")
play_loop_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "play_loop.png")
next_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "next_frame_s.png")
next_trim_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "next_frame_trim.png")
prev_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "prev_frame_s.png")
prev_trim_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "prev_frame_trim.png")
stop_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "stop_s.png")
stop_trim_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "stop_loop.png")
# --------------------------------- player
def refresh_player():
# First event is initial window displayed event.
# Last closing event needs to be blocked by setting this flag
# before calling window hide
global player_refresh_enabled
if not player_refresh_enabled:
player_refresh_enabled = True
return
# Refreshing while rendering overwrites file on disk and loses
# previous rendered data.
if PLAYER().is_rendering:
return
PLAYER().refresh()
# --------------------------------- window
def window_resized():
# This can get async called from window "size-allocate" signal
# during project load before project.c_seq has been build
if not(hasattr(editorstate.project, "c_seq")):
return
if editorstate.project.c_seq == None:
return
# Resize track heights so that all tracks are displayed
current_sequence().resize_tracks_to_fit(gui.tline_canvas.widget.allocation)
# Place clips in the middle of timeline canvas after window resize
tlinewidgets.set_ref_line_y(gui.tline_canvas.widget.allocation)
gui.tline_column.init_listeners() # hit areas for track swicthes need to be recalculated
repaint_tline()
# --------------------------------- timeline
# --- REPAINT
def repaint_tline():
"""
Repaints timeline canvas and scale
"""
gui.tline_canvas.widget.queue_draw()
gui.tline_scale.widget.queue_draw()
# --- SCROLL AND LENGTH EVENTS
def update_tline_scrollbar():
"""
Sets timeline scrollwidget bar size and position
"""
# Calculate page size
# page_size / 100.0 == scroll bar size / scroll track width
update_pix_per_frame_full_view()
global page_size
if tlinewidgets.pix_per_frame < pix_per_frame_full_view:
page_size = 100.0
else:
page_size = (float(pix_per_frame_full_view) / \
tlinewidgets.pix_per_frame) * 100.0
# Get position, this might get called before GUI initiated
try:
old_adjustment = gui.tline_scroll.get_adjustment()
pos = old_adjustment.get_value()
except Exception:
pos = 0.0
# Create and set adjustment
adjustment = gtk.Adjustment(pos, 0.0, 100.0,
1.0, 10.0, page_size)
adjustment.connect("value-changed", tline_scrolled)
try: # when testing this might get called before gui is build
gui.tline_scroll.set_adjustment(adjustment)
except Exception:
pass
def tline_scrolled(adjustment):
"""
Callback from timeline scroller widget
"""
if page_size != 100.0:
tlinewidgets.pos = ((adjustment.get_value() / 100.0) *
current_sequence().get_length())
else:
tlinewidgets.pos = 0
repaint_tline()
def center_tline_to_current_frame():
"""
Sets scroll widget adjustment to place current frame in the middle of display.
"""
pos = tlinewidgets.get_pos_for_tline_centered_to_current_frame()
gui.tline_scroll.get_adjustment().set_value((float(pos) / float(current_sequence().get_length())) * 100.0)
def init_tline_scale():
"""
Calculates and sets first scale quaranteed to display full view
when starting from PIX_PER_FRAME_MAX with SCALE_MULTIPLIER steps.
"""
pix_per_frame = PIX_PER_FRAME_MAX
while pix_per_frame > pix_per_frame_full_view:
pix_per_frame *= SCALE_MULTIPLIER
tlinewidgets.pix_per_frame = pix_per_frame
def update_pix_per_frame_full_view():
"""
Sets the value of pix_per_frame_full_view
Called at sequence init to display full sequence.
"""
global pix_per_frame_full_view
length = current_sequence().get_length() + 5 # +5 is just selected end pad so that end of movie is visible
x, y, w, h = gui.tline_canvas.widget.allocation
pix_per_frame_full_view = float(w) / length
def set_info_icon(info_icon_id):
if info_icon_id == None:
widget = gtk.Label()
else:
widget = gtk.image_new_from_stock(info_icon_id, gtk.ICON_SIZE_MENU)
gui.tline_info.remove(gui.tline_info.info_contents)
gui.tline_info.add(widget)
gui.tline_info.info_contents = widget
widget.show()
# --- ZOOM
def zoom_in():
"""
Zooms in in the timeline view.
"""
tlinewidgets.pix_per_frame *= 1.0 / SCALE_MULTIPLIER
if tlinewidgets.pix_per_frame > PIX_PER_FRAME_MAX:
tlinewidgets.pix_per_frame = PIX_PER_FRAME_MAX
repaint_tline()
update_tline_scrollbar()
center_tline_to_current_frame()
def zoom_out():
"""
Zooms out in the timeline view.
"""
tlinewidgets.pix_per_frame *= SCALE_MULTIPLIER
if tlinewidgets.pix_per_frame < PIX_PER_FRAME_MIN:
tlinewidgets.pix_per_frame = PIX_PER_FRAME_MIN
repaint_tline()
update_tline_scrollbar()
center_tline_to_current_frame()
def zoom_max():
tlinewidgets.pix_per_frame = PIX_PER_FRAME_MAX
repaint_tline()
update_tline_scrollbar()
center_tline_to_current_frame()
def zoom_project_length():
tlinewidgets.pos = 0
update_pix_per_frame_full_view()
init_tline_scale()
repaint_tline()
update_tline_scrollbar()
def mouse_scroll_zoom(event):
if event.state & gtk.gdk.CONTROL_MASK:
adj = gui.tline_scroll.get_adjustment()
incr = adj.get_step_increment()
if event.direction == gtk.gdk.SCROLL_UP:
adj.set_value(adj.get_value() + incr)
else:
adj.set_value(adj.get_value() - incr)
else:
if event.direction == gtk.gdk.SCROLL_UP:
zoom_in()
else:
zoom_out()
def maybe_autocenter():
if timeline_visible():
if editorpersistance.prefs.auto_center_on_play_stop == True:
center_tline_to_current_frame()
# ----------------------------------------- monitor
def display_clip_in_monitor(clip_monitor_currently_active=False):
"""
Sets mltplayer producer to be video file clip and updates GUI.
"""
if MONITOR_MEDIA_FILE() == None:
gui.editor_window.clip_editor_b.set_active(False)
return
global save_monitor_frame
save_monitor_frame = True
# Opening clip exits trim modes
if not editorstate.current_is_move_mode():
set_clip_edit_mode_callback()
gui.clip_editor_b.set_sensitive(True)
editorstate._timeline_displayed = False
# Save timeline pos if so directed.
if clip_monitor_currently_active == False:
global saved_timeline_pos
saved_timeline_pos = PLAYER().current_frame()
editorstate.tline_shadow_frame = saved_timeline_pos
# If we're already displaying monitor clip we stop consumer
# to supress timeline flashing between monitor clips
if clip_monitor_currently_active == False:
editorstate.PLAYER().consumer.stop()
# Clear old clip
current_sequence().clear_hidden_track()
# Create and display clip on hidden track
if MONITOR_MEDIA_FILE().type == appconsts.PATTERN_PRODUCER or MONITOR_MEDIA_FILE().type == appconsts.IMAGE_SEQUENCE:
# pattern producer or image sequence
clip_producer = current_sequence().display_monitor_clip(None, MONITOR_MEDIA_FILE())
else:
# File producers
clip_producer = current_sequence().display_monitor_clip(MONITOR_MEDIA_FILE().path)
# Timeline flash does not happen if we start consumer after monitor clip is
# already on sequence
if clip_monitor_currently_active == False:
editorstate.PLAYER().consumer.start()
# IMAGE_SEQUENCE files always returns 15000 for get_length from mlt so we have to monkeypatch that method to get correct results
if MONITOR_MEDIA_FILE().type == appconsts.IMAGE_SEQUENCE:
clip_producer.get_length = lambda : MONITOR_MEDIA_FILE().length
clip_producer.mark_in = MONITOR_MEDIA_FILE().mark_in
clip_producer.mark_out = MONITOR_MEDIA_FILE().mark_out
# Give IMAGE and PATTERN_PRODUCER media types default mark in and mark out if not already set.
# This makes them reasonably short and trimmable in both directions.
if clip_producer.media_type == appconsts.IMAGE or clip_producer.media_type == appconsts.PATTERN_PRODUCER:
if clip_producer.mark_in == -1 and clip_producer.mark_out == -1:
center_frame = clip_producer.get_length() / 2
default_length_half = 75
mark_in = center_frame - default_length_half
mark_out = center_frame + default_length_half - 1
clip_producer.mark_in = mark_in
clip_producer.mark_out = mark_out
MONITOR_MEDIA_FILE().mark_in = mark_in
MONITOR_MEDIA_FILE().mark_out = mark_out
display_monitor_clip_name()
# Display frame, marks and pos
gui.pos_bar.update_display_from_producer(clip_producer)
if MONITOR_MEDIA_FILE().type == appconsts.IMAGE or \
MONITOR_MEDIA_FILE().type == appconsts.PATTERN_PRODUCER:
PLAYER().seek_frame(0)
else:
if editorpersistance.prefs.remember_monitor_clip_frame:
PLAYER().seek_frame(MONITOR_MEDIA_FILE().current_frame)
else:
PLAYER().seek_frame(0)
display_marks_tc()
gui.pos_bar.widget.grab_focus()
gui.media_list_view.widget.queue_draw()
if editorpersistance.prefs.auto_play_in_clip_monitor == True:
PLAYER().start_playback()
repaint_tline()
def display_monitor_clip_name():
# Display clip name
if MONITOR_MEDIA_FILE().mark_in != -1 and MONITOR_MEDIA_FILE().mark_out != -1:
clip_length = utils.get_tc_string(MONITOR_MEDIA_FILE().mark_out - MONITOR_MEDIA_FILE().mark_in + 1) #+1 out incl.
range_text = " / ][ " + str(clip_length)
else:
range_text = ""
gui.editor_window.monitor_source.set_text(MONITOR_MEDIA_FILE().name + range_text)
def display_sequence_in_monitor():
"""
Sets mltplayer producer to be current sequence
tractor and updates GUI.
"""
if PLAYER() == None: # this method gets called too early when initializing, hack fix.
return
# If this gets called without user having pressed 'Timeline' button we'll
# programmatically press it to recall this method to have the correct button down.
if gui.sequence_editor_b.get_active() == False:
gui.sequence_editor_b.set_active(True)
return
editorstate._timeline_displayed = True
# Clear hidden track that has been displaying monitor clip
current_sequence().clear_hidden_track()
# Reset timeline pos
global saved_timeline_pos
if saved_timeline_pos != -1:
PLAYER().seek_frame(saved_timeline_pos)
saved_timeline_pos = -1
# Display sequence name
name = editorstate.current_sequence().name
profile_desc = editorstate.current_sequence().profile.description()
if editorpersistance.prefs.show_sequence_profile:
gui.editor_window.monitor_source.set_text(name + " / " + profile_desc)
else:
gui.editor_window.monitor_source.set_text(name)
# Display marks and pos
gui.pos_bar.update_display_from_producer(PLAYER().producer)
display_marks_tc()
repaint_tline()
def switch_monitor_display():
monitorevent.stop_pressed()
if editorstate.MONITOR_MEDIA_FILE() == None:
return
if editorstate._timeline_displayed == True:
gui.editor_window.clip_editor_b.set_active(True)
else:
gui.editor_window.sequence_editor_b.set_active(True)
def display_tline_cut_frame(track, index):
"""
Displays sequence frame at cut
"""
if not timeline_visible():
display_sequence_in_monitor()
if index < 0:
index = 0
if index > (len(track.clips) - 1):
index = len(track.clips) - 1
clip_start_frame = track.clip_start(index)
PLAYER().seek_frame(clip_start_frame)
def media_file_row_double_clicked(treeview, tree_path, col):
gui.tline_canvas.widget.grab_focus()
row = max(tree_path)
media_file_id = editorstate.current_bin().file_ids[row]
media_file = PROJECT().media_files[media_file_id]
set_and_display_monitor_media_file(media_file)
def set_and_display_monitor_media_file(media_file):
"""
Displays media_file in clip monitor when new media file
selected for display by double clicking or drag'n'drop
"""
editorstate._monitor_media_file = media_file
# If we're already displaying clip monitor, then already button is down we call display_clip_in_monitor(..)
# directly, but dont save position because we're not displaying now.
#
# If we're displaying sequence we do programmatical click on "Clip" button
# to display clip via it's signal listener.
if gui.editor_window.clip_editor_b.get_active() == True:
display_clip_in_monitor(clip_monitor_currently_active = True)
else:
gui.editor_window.clip_editor_b.set_active(True)
# --------------------------------------- frame displayes
def update_frame_displayers(frame):
"""
Display frame position in position bar and time code display.
"""
# Update position bar with normalized pos
if timeline_visible():
producer_length = PLAYER().producer.get_length()
else:
producer_length = gui.pos_bar.producer.get_length()
if save_monitor_frame:
MONITOR_MEDIA_FILE().current_frame = frame
norm_pos = frame / float(producer_length)
gui.pos_bar.set_normalized_pos(norm_pos)
gui.tline_scale.widget.queue_draw()
gui.tline_canvas.widget.queue_draw()
gui.big_tc.widget.queue_draw()
clipeffectseditor.display_kfeditors_tline_frame(frame)
compositeeditor.display_kfeditors_tline_frame(frame)
def update_kf_editor():
clipeffectseditor.update_kfeditors_positions()
# ----------------------------------------- marks
def display_marks_tc():
if not timeline_visible():
display_monitor_clip_name()
# ----------------------------------------------- clip editors
def clip_removed_during_edit(clip):
clipeffectseditor.clip_removed_during_edit(clip)
def clear_clip_from_editors(clip):
if clipeffectseditor.clip == clip:
clipeffectseditor.clear_clip()
def open_clip_in_effects_editor(data):
clip, track, item_id, x = data
frame = tlinewidgets.get_frame(x)
index = current_sequence().get_clip_index(track, frame)
clipeffectseditor.set_clip(clip, track, index)
# ----------------------------------------- edit modes
def set_trim_mode_gui():
"""
Called when user selects trim mode
"""
display_sequence_in_monitor()
def set_move_mode_gui():
"""
Called when user selects move mode
"""
display_sequence_in_monitor()
def set_transition_render_edit_menu_items_sensitive(range_start, range_end):
if not editorstate.current_is_move_mode():
return
ui = gui.editor_window.uimanager
render_transition = ui.get_widget('/MenuBar/EditMenu/AddTransition')
render_fade = ui.get_widget('/MenuBar/EditMenu/AddFade')
if range_start == -1:
render_transition.set_sensitive(False)
render_fade.set_sensitive(False)
elif range_start == range_end:
render_transition.set_sensitive(False)
render_fade.set_sensitive(True)
elif range_start == range_end - 1:
render_transition.set_sensitive(True)
render_fade.set_sensitive(False)
else:
render_transition.set_sensitive(False)
render_fade.set_sensitive(False)
# ------------------------------------------------ notebook
def switch_notebook_panel(index):
gui.middle_notebook.set_current_page(index)
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module contains GUI components for displayingand editing clips in timeline.
Global display position and scale information is in this module.
"""
import cairo
import pygtk
pygtk.require('2.0');
import gtk
import math
import pango
import pangocairo
import appconsts
from cairoarea import CairoDrawableArea
import clipeffectseditor
import editorpersistance
from editorstate import current_sequence
from editorstate import timeline_visible
from editorstate import PLAYER
from editorstate import EDIT_MODE
from editorstate import current_proxy_media_paths
import editorstate
import respaths
import sequence
import trimmodes
import utils
import updater
M_PI = math.pi
REF_LINE_Y = 250 # Y pos of tracks are relative to this. This is recalculated on initilization, so value here is irrelevent.
WIDTH = 430 # this has no effect if smaller then editorwindow.NOTEBOOK_WIDTH + editorwindow.MONITOR_AREA_WIDTH
HEIGHT = 260 # defines window min height together with editorwindow.TOP_ROW_HEIGHT
# Timeline draw constants
# Other elements than black outline are not drawn if clip screen size
# in pixels is below certain thresholds
TEXT_MIN = 12 # if clip shorter, no text
EMBOSS_MIN = 8 # if clip shorter, no emboss
FILL_MIN = 1 # if clip shorter, no fill
TEXT_X = 6 # pos for clip text
TEXT_Y = 29
TEXT_Y_SMALL = 17
WAVEFORM_PAD_LARGE = 9
WAVEFORM_PAD_SMALL = 4
MARK_PAD = 6
MARK_LINE_WIDTH = 4
# tracks column consts
COLUMN_WIDTH = 96 # column area width
SCALE_HEIGHT = 25
SCROLL_HEIGHT = 20
COLUMN_LEFT_PAD = 4 # as mute switch no longer exists this is now essentially left pad width
ACTIVE_SWITCH_WIDTH = 18
COMPOSITOR_HEIGHT_OFF = 10
COMPOSITOR_HEIGHT = 20
COMPOSITOR_TEXT_X = 6
COMPOSITOR_TEXT_Y = 15
COMPOSITOR_TRACK_X_PAD = 4
COMPOSITOR_TRACK_ARROW_WIDTH = 6
COMPOSITOR_TRACK_ARROW_HEAD_WIDTH = 10
COMPOSITOR_TRACK_ARROW_HEAD_WIDTH_HEIGHT = 5
ID_PAD_X = 29 # track id text pos
ID_PAD_Y = 16 # track id text pos
ID_PAD_Y_SMALL = 4 # track id text pos for small track
VIDEO_TRACK_V_ICON_POS = (5, 16)
VIDEO_TRACK_A_ICON_POS = (5, 25)
VIDEO_TRACK_V_ICON_POS_SMALL = (5, 3)
VIDEO_TRACK_A_ICON_POS_SMALL = (5, 12)
AUDIO_TRACK_ICON_POS = (5, 18)
AUDIO_TRACK_ICON_POS_SMALL = (5, 6)
MUTE_ICON_POS = (5, 4)
MUTE_ICON_POS_NORMAL = (5, 14)
LOCK_POS = (67, 2)
INSRT_ICON_POS = (81, 18)
INSRT_ICON_POS_SMALL = (81, 6)
# tracks column icons
FULL_LOCK_ICON = None
TRACK_BG_ICON = None
MUTE_VIDEO_ICON = None
MUTE_AUDIO_ICON = None
MUTE_AUDIO_A_ICON = None
MUTE_ALL_ICON = None
TRACK_ALL_ON_V_ICON = None
TRACK_ALL_ON_A_ICON = None
# clip icons
FILTER_CLIP_ICON = None
COMPOSITOR_CLIP_ICON = None
VIEW_SIDE_ICON = None
INSERT_ARROW_ICON = None
AUDIO_MUTE_ICON = None
VIDEO_MUTE_ICON = None
ALL_MUTE_ICON = None
MARKER_ICON = None
# tc scale
TC_POINTER_HEAD = None
# tc frame scale consts
SCALE_LINE_Y = 4.5 # scale horizontal line pos
SMALL_TICK_Y = 18.5 # end for tick drawn in all scales
BIG_TICK_Y = 12.5 # end for tick drawn in most zoomed in scales
TC_Y = 10 # TC text pos in scale
# Timeline scale is rendered with hardcoded steps for hardcoded
# pix_per_frame ranges
DRAW_THRESHOLD_1 = 6 # if pix_per_frame below this, draw secs
DRAW_THRESHOLD_2 = 4
DRAW_THRESHOLD_3 = 2
DRAW_THRESHOLD_4 = 1
# Height of sync state stripe indicating if clip is in sync or not
SYNC_STRIPE_HEIGHT = 12
SYNC_SAW_WIDTH = 5
SYNC_SAW_HEIGHT = 5
# number on lines and tc codes displayed with small pix_per_frame values
NUMBER_OF_LINES = 7
# Positions for 1-2 icons on clips.
ICON_SLOTS = [(14, 2),(28, 2),(42,2),(56,2)]
# Line width for moving clip boxes
MOVE_CLIPS_LINE_WIDTH = 3.0
# Color creating utils methods
def get_multiplied_color(color, m):
"""
Used to create lighter and darker hues of colors.
"""
return (color[0] * m, color[1] * m, color[2] * m)
def get_multiplied_grad(pos, alpha, grad_color, m):
"""
Used to create lighter and darker hues of gradient colors.
"""
return (pos, grad_color[1] * m, grad_color[2] * m, grad_color[3] * m, alpha)
def get_multiplied_color_from_grad(grad_color, m):
"""
Used to create lighter and darker hues of gradient colors.
"""
return (grad_color[1] * m, grad_color[2] * m, grad_color[3] * m)
# Colors
GRAD_MULTIPLIER = 1.3
SELECTED_MULTIPLIER = 1.52
CLIP_COLOR = (0.62, 0.38, 0.7)
CLIP_COLOR_L = get_multiplied_color(CLIP_COLOR, GRAD_MULTIPLIER)
CLIP_COLOR_GRAD = (1, 0.62, 0.38, 0.7, 1)
CLIP_COLOR_GRAD_L = get_multiplied_grad(0, 1, CLIP_COLOR_GRAD, GRAD_MULTIPLIER)
CLIP_SELECTED_COLOR = get_multiplied_color_from_grad(CLIP_COLOR_GRAD, SELECTED_MULTIPLIER)
AUDIO_CLIP_COLOR_GRAD = (1, 0.23, 0.52, 0.23, 1)#(1, 0.79, 0.80, 0.18, 1)
AUDIO_CLIP_COLOR_GRAD_L = get_multiplied_grad(0, 1, AUDIO_CLIP_COLOR_GRAD, GRAD_MULTIPLIER + 0.5)
AUDIO_CLIP_SELECTED_COLOR = (0.53, 0.85, 0.53)
IMAGE_CLIP_SELECTED_COLOR = (0.45, 0.90, 0.93)
IMAGE_CLIP_COLOR_GRAD = (1, 0.33, 0.65, 0.69, 1)
IMAGE_CLIP_COLOR_GRAD_L = get_multiplied_grad(0, 1, IMAGE_CLIP_COLOR_GRAD, GRAD_MULTIPLIER)
COMPOSITOR_CLIP = (0.3, 0.3, 0.3, 0.8)
COMPOSITOR_CLIP_SELECTED = (0.5, 0.5, 0.7, 0.8)
BLANK_CLIP_COLOR_GRAD = (1, 0.6, 0.6, 0.65, 1)
BLANK_CLIP_COLOR_GRAD_L = (0, 0.6, 0.6, 0.65, 1)
BLANK_CLIP_COLOR_SELECTED_GRAD = (1, 0.7, 0.7, 0.75, 1)
BLANK_CLIP_COLOR_SELECTED_GRAD_L = (0, 0.7, 0.7, 0.75, 1)
SINGLE_TRACK_TRANSITION_SELECTED = (0.8, 0.8, 1.0)
SYNC_OK_COLOR = (0.18, 0.55, 0.18)
SYNC_OFF_COLOR = (0.77, 0.20, 0.3)
SYNC_GONE_COLOR = (0.4, 0.4, 0.4)
PROXY_STRIP_COLOR = (0.40, 0.60, 0.82)
MARK_COLOR = (0.1, 0.1, 0.1)
FRAME_SCALE_COLOR_GRAD = (1, 0.8, 0.8, 0.8, 1)
FRAME_SCALE_COLOR_GRAD_L = get_multiplied_grad(0, 1, FRAME_SCALE_COLOR_GRAD, GRAD_MULTIPLIER)
FRAME_SCALE_SELECTED_COLOR_GRAD = get_multiplied_grad(0, 1, FRAME_SCALE_COLOR_GRAD, 0.92)
FRAME_SCALE_SELECTED_COLOR_GRAD_L = get_multiplied_grad(1, 1, FRAME_SCALE_SELECTED_COLOR_GRAD, GRAD_MULTIPLIER)
DARK_FRAME_SCALE_SELECTED_COLOR_GRAD = get_multiplied_grad(0, 1, FRAME_SCALE_COLOR_GRAD, 0.7)
DARK_FRAME_SCALE_SELECTED_COLOR_GRAD_L = get_multiplied_grad(1, 1, FRAME_SCALE_SELECTED_COLOR_GRAD, GRAD_MULTIPLIER * 0.8)
FRAME_SCALE_LINES = (0, 0, 0)
BG_COLOR = (0.5, 0.5, 0.55)#(0.6, 0.6, 0.65)
TRACK_BG_COLOR = (0.25, 0.25, 0.27)#(0.6, 0.6, 0.65)
COLUMN_ACTIVE_COLOR = (0.36, 0.37, 0.37)
COLUMN_NOT_ACTIVE_COLOR = (0.65, 0.65, 0.65)
OVERLAY_COLOR = (0.9,0.9,0.9)
OVERLAY_SELECTION_COLOR = (0.9,0.9,0.0)
CLIP_OVERLAY_COLOR = (0.2, 0.2, 0.9, 0.5)
OVERWRITE_OVERLAY_COLOR = (0.2, 0.2, 0.2, 0.5)
INSERT_MODE_COLOR = (0.9,0.9,0.0)
OVERWRITE_MODE_COLOR = (0.9,0.0,0.0)
POINTER_TRIANGLE_COLOR = (0.6, 0.7, 0.8, 0.7)
SHADOW_POINTER_COLOR = (0.5, 0.5, 0.5)
BLANK_SELECTED = (0.68, 0.68, 0.74)
TRACK_GRAD_STOP1 = (1, 0.68, 0.68, 0.68, 1) #0.93, 0.93, 0.93, 1)
TRACK_GRAD_STOP2 = (0.5, 0.93, 0.93, 0.93, 1) # (0.5, 0.58, 0.58, 0.58, 1)
TRACK_GRAD_STOP3 = (0, 0.93, 0.93, 0.93, 1) #0.58, 0.58, 0.58, 1) #(0, 0.84, 0.84, 0.84, 1)
TRACK_GRAD_ORANGE_STOP1 = (1, 0.4, 0.4, 0.4, 1)
TRACK_GRAD_ORANGE_STOP2 = (1, 0.93, 0.62, 0.53, 1) #(0.5, 0.58, 0.34, 0.34, 1)
TRACK_GRAD_ORANGE_STOP3 = (0, 0.68, 0.68, 0.68, 1)
LIGHT_MULTILPLIER = 1.14
DARK_MULTIPLIER = 0.74
POINTER_COLOR = (1, 0.3, 0.3) # red frame pointer for position bar
# ------------------------------------------------------------------ MODULE STATE
# debug purposes
draw_blank_borders = True
# Draw state
pix_per_frame = 5.0 # Current draw scale. This set set elsewhere on init so default value irrelevant.
pos = 0 # Current left most frame in timeline display
# ref to singleton TimeLineCanvas instance for mode setting and some position
# calculations.
canvas_widget = None
# Used to draw trim modes differently when moving from <X>_NO_EDIT mode to active edit
trim_mode_in_non_active_state = False
# Used ahen editing with SLIDE_TRIM mode to make user believe that the frame being displayed
# is the view frame user selected while in reality user is displayed images from hidden track and the
# current frame is moving in opposite direction to users mouse movement
fake_current_frame = None
# Used to draw indicators that tell if more frames are available while trimming
trim_status = appconsts.ON_BETWEEN_FRAME
# ------------------------------------------------------------------- module functions
def load_icons():
global FULL_LOCK_ICON, FILTER_CLIP_ICON, VIEW_SIDE_ICON,\
COMPOSITOR_CLIP_ICON, INSERT_ARROW_ICON, AUDIO_MUTE_ICON, MARKER_ICON, \
VIDEO_MUTE_ICON, ALL_MUTE_ICON, TRACK_BG_ICON, MUTE_AUDIO_ICON, MUTE_VIDEO_ICON, MUTE_ALL_ICON, \
TRACK_ALL_ON_V_ICON, TRACK_ALL_ON_A_ICON, MUTE_AUDIO_A_ICON, TC_POINTER_HEAD, EDIT_INDICATOR
FULL_LOCK_ICON = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "full_lock.png")
FILTER_CLIP_ICON = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "filter_clip_icon_sharp.png")
COMPOSITOR_CLIP_ICON = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "compositor.png")
VIEW_SIDE_ICON = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "view_side.png")
INSERT_ARROW_ICON = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "insert_arrow.png")
AUDIO_MUTE_ICON = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "clip_audio_mute.png")
VIDEO_MUTE_ICON = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "clip_video_mute.png")
ALL_MUTE_ICON = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "clip_all_mute.png")
TRACK_BG_ICON = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "track_bg.png")
MUTE_AUDIO_ICON = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "track_audio_mute.png")
MUTE_VIDEO_ICON = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "track_video_mute.png")
MUTE_ALL_ICON = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "track_all_mute.png")
MARKER_ICON = _load_pixbuf("marker.png")
TRACK_ALL_ON_V_ICON = _load_pixbuf("track_all_on_V.png")
TRACK_ALL_ON_A_ICON = _load_pixbuf("track_all_on_A.png")
MUTE_AUDIO_A_ICON = _load_pixbuf("track_audio_mute_A.png")
TC_POINTER_HEAD = _load_pixbuf("tc_pointer_head.png")
EDIT_INDICATOR = _load_pixbuf("clip_edited.png")
if editorpersistance.prefs.dark_theme == True:
global FRAME_SCALE_COLOR_GRAD, FRAME_SCALE_COLOR_GRAD_L, BG_COLOR, FRAME_SCALE_LINES
FRAME_SCALE_COLOR_GRAD = (1, 0.3, 0.3, 0.3, 1)
FRAME_SCALE_COLOR_GRAD_L = get_multiplied_grad(0, 1, FRAME_SCALE_COLOR_GRAD, GRAD_MULTIPLIER)
BG_COLOR = (0.44, 0.44, 0.46)
FRAME_SCALE_LINES = (0.8, 0.8, 0.8)
def _load_pixbuf(icon_file):
return gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + icon_file)
def set_ref_line_y(allocation):
"""
Sets value of REF_LINE_Y to such that tracks are vertically centered.
"""
total_h = 0
below_ref_h = 0
for i in range(1, len(current_sequence().tracks) - 1):
total_h += current_sequence().tracks[i].height
if i < current_sequence().first_video_index:
below_ref_h += current_sequence().tracks[i].height
x, y, w, panel_height = allocation
centerered_tracks_bottom_y = (panel_height / 2.0) + (total_h / 2.0)
global REF_LINE_Y
REF_LINE_Y = centerered_tracks_bottom_y - below_ref_h
def get_pos_for_tline_centered_to_current_frame():
current_frame = PLAYER().current_frame()
x, y, w, h = canvas_widget.widget.allocation
frames_in_panel = w / pix_per_frame
# current in first half on first screen width of tline display
if current_frame < (frames_in_panel / 2.0):
return 0
else:
return current_frame - (frames_in_panel / 2)
def get_frame(panel_x):
"""
Returns frame for panel x position
"""
return int(pos + (panel_x / pix_per_frame))
def get_track(panel_y):
"""
Returns track object for y or None
"""
audio_add = 0
for i in range(1, current_sequence().first_video_index):
audio_add = audio_add + current_sequence().tracks[i].height
bottom_line = REF_LINE_Y + audio_add
if panel_y > bottom_line:
return None
tracks_height = bottom_line;
for i in range(1, len(current_sequence().tracks)):
tracks_height = tracks_height - current_sequence().tracks[i].height
if tracks_height < panel_y:
return current_sequence().tracks[i]
return None
def get_clip_track_and_index_for_pos(x, y):
# Returns tuple (clip, track, index)
track = get_track(y)
if track == None:
return (None, None, -1)
frame = get_frame(x)
clip_index = current_sequence().get_clip_index(track, frame)
if clip_index == -1:
return (None, None, -1)
return (track.clips[clip_index], track, clip_index)
def _get_track_y(track_index):
"""
NOTE: NOT REALLY INTERNAL TO MODULE, HAS OUTSIDE USERS.
Returns y pos in canvas for track index. y is top most pixel in track
"""
audio_add = 0
for i in range(1, current_sequence().first_video_index):
audio_add = audio_add + current_sequence().tracks[i].height
bottom_line = REF_LINE_Y + audio_add
tracks_height = 0;
for i in range(1, track_index + 1):
tracks_height = tracks_height + current_sequence().tracks[i].height
return bottom_line - tracks_height
def _get_frame_x(frame):
"""
NOTE: NOT REALLY INTERNAL TO MODULE, HAS OUTSIDE USERS.
Returns x pos in canvas for timeline frame
"""
disp_frame = frame - pos
return disp_frame * pix_per_frame
def compositor_hit(frame, y, sorted_compositors):
"""
Returns compositor hit with mouse press x,y or None if nothing hit.
"""
track = get_track(y)
try:
track_top = _get_track_y(track.id)
except AttributeError: # we didn't press on a editable track
return None
# Test if compositor hit on track top, so compositor hit on dest track side
if y >= track_top and y < track_top + (COMPOSITOR_HEIGHT - COMPOSITOR_HEIGHT_OFF):
return _comp_hit_on_below_track(frame, track, sorted_compositors)
# Test if compositor hit on track bottom, so compositor hit on source track side
elif y >= (track_top + track.height - COMPOSITOR_HEIGHT_OFF) and y <=(track_top + track.height):
return _comp_hit_on_source_track(frame, track, sorted_compositors)
# Hit y is on he stripe where no compositors can be hit
else:
return None
def _comp_hit_on_below_track(frame, track, sorted_compositors):
for comp in sorted_compositors:
if comp.transition.b_track - 1 == track.id:
if comp.clip_in <= frame and comp.clip_out >= frame:
return comp
return None
def _comp_hit_on_source_track(frame, track, sorted_compositors):
for comp in sorted_compositors:
if comp.transition.b_track == track.id:
if comp.clip_in <= frame and comp.clip_out >= frame:
return comp
return None
# --------------------------------------- edit mode overlay draw handling
def set_edit_mode(data, draw_func):
global canvas_widget
canvas_widget.edit_mode_data = data
canvas_widget.edit_mode_overlay_draw_func = draw_func
def set_edit_mode_data(data):
global canvas_widget
canvas_widget.edit_mode_data = data
def draw_insert_overlay(cr, data):
"""
Overlay for insert move edit mode
"""
# Only draw if were moving
if data == None:
return
if data["move_on"] == False:
return
target_track = data["to_track_object"]
y = _get_track_y(target_track.id)
_draw_move_overlay(cr, data, y)
insert_frame = data["insert_frame"]
insert_frame_x = _get_frame_x(insert_frame)
_draw_mode_arrow(cr, insert_frame_x, y, INSERT_MODE_COLOR)
def draw_overwrite_overlay(cr, data):
# Only draw if were moving
if data == None:
return
if data["move_on"] == False:
return
target_track = data["to_track_object"]
y = _get_track_y(target_track.id)
start_x = _get_frame_x(data["over_in"])
end_x = _get_frame_x(data["over_out"])
track_height = target_track.height
_draw_overwrite_clips_overlay(cr, start_x, end_x, y, track_height)
_draw_move_overlay(cr, data, y)
arrow_x = start_x + ((end_x - start_x)/2.0)
_draw_mode_arrow(cr, arrow_x, y, OVERWRITE_MODE_COLOR)
def _draw_move_overlay(cr, data, y):
# Get data
press_frame = data["press_frame"]
current_frame = data["current_frame"]
first_clip_start = data["first_clip_start"]
clip_lengths = data["clip_lengths"]
track_height = data["to_track_object"].height
# Get first frame for drawing shadow clips
draw_start = first_clip_start + (current_frame - press_frame)
clip_start_frame = draw_start - pos
# Draw clips in draw range
cr.set_line_width(MOVE_CLIPS_LINE_WIDTH)
cr.set_source_rgb(*OVERLAY_COLOR)
for i in range(0, len(clip_lengths)):
clip_length = clip_lengths[i]
scale_length = clip_length * pix_per_frame
scale_in = clip_start_frame * pix_per_frame
cr.rectangle(scale_in, y + 1.5, scale_length, track_height - 2.5)
cr.stroke()
# Start frame for next clip
clip_start_frame += clip_length
def draw_multi_overlay(cr, data):
if data == None:
return
press_frame = data["press_frame"]
current_frame = data["current_frame"]
min_allowed_delta = - data["multi_data"].max_backwards
first_moved_frame = data["first_moved_frame"]
move_all = data["multi_data"].move_all_tracks
delta = current_frame - press_frame
if delta <= min_allowed_delta:
delta = min_allowed_delta
can_move_back = False
else:
can_move_back = True
draw_y = _get_track_y(0) + 100
cr.set_line_width(1.0)
first_frame = first_moved_frame - pos
first_x = first_frame * pix_per_frame
draw_frame = first_moved_frame + delta - pos
draw_x = draw_frame * pix_per_frame
if move_all:
cr.rectangle(first_x, 0, draw_x - first_x, draw_y)
cr.set_source_rgba(0,0,0,0.2)
cr.fill()
cr.set_source_rgb(*OVERLAY_COLOR)
cr.move_to(draw_x, 0)
cr.line_to(draw_x, draw_y)
cr.stroke()
else:
moved_track_index = data["multi_data"].pressed_track_id
draw_y = _get_track_y(moved_track_index)
h = current_sequence().tracks[moved_track_index].height
cr.rectangle(first_x, draw_y, draw_x - first_x, h)
cr.set_source_rgba(0,0,0,0.2)
cr.fill()
cr.set_source_rgb(*OVERLAY_COLOR)
cr.move_to(draw_x, draw_y - 5)
cr.line_to(draw_x, draw_y + h + 10)
cr.stroke()
tracks = current_sequence().tracks
track_moved = data["multi_data"].track_affected
for i in range(1, len(tracks) - 1):
if not track_moved[i - 1]:
continue
track = tracks[i]
draw_y = _get_track_y(i) + track.height / 2
cr.move_to(draw_x + 2, draw_y)
cr.line_to(draw_x + 2, draw_y - 5)
cr.line_to(draw_x + 7, draw_y)
cr.line_to(draw_x + 2, draw_y + 5)
cr.close_path()
cr.fill()
if can_move_back:
cr.move_to(draw_x - 2, draw_y)
cr.line_to(draw_x - 2, draw_y - 5)
cr.line_to(draw_x - 7, draw_y)
cr.line_to(draw_x - 2, draw_y + 5)
cr.close_path()
cr.fill()
def draw_two_roll_overlay(cr, data):
edit_frame = data["edit_frame"]
frame_x = _get_frame_x(edit_frame)
track_height = current_sequence().tracks[data["track"]].height
track_y = _get_track_y(data["track"])
cr.set_source_rgb(*OVERLAY_COLOR)
cr.move_to(frame_x, track_y - 3)
cr.line_to(frame_x, track_y + track_height + 3)
cr.stroke()
selection_frame_x = _get_frame_x(data["selected_frame"])
cr.set_source_rgb(*OVERLAY_SELECTION_COLOR)
cr.move_to(selection_frame_x - 0.5, track_y - 6.5)
cr.line_to(selection_frame_x - 0.5, track_y + track_height + 6.5)
cr.stroke()
if data["to_side_being_edited"]:
_draw_view_icon(cr, frame_x + 6, track_y + 1)
else:
_draw_view_icon(cr, frame_x - 18, track_y + 1)
trim_limits = data["trim_limits"]
clip_over_start_x = _get_frame_x(trim_limits["both_start"] - 1) # trim limits leave 1 frame non-trimmable
clip_over_end_x = _get_frame_x(trim_limits["both_end"] + 1) # trim limits leave 1 frame non-trimmable
cr.set_line_width(2.0)
_draw_trim_clip_overlay(cr, clip_over_start_x, clip_over_end_x, track_y, track_height, False, (1,1,1,0.3))
cr.set_line_width(1.0)
cr.move_to(clip_over_start_x - 0.5, track_y - 6.5)
cr.line_to(clip_over_start_x - 0.5, track_y + track_height + 6.5)
cr.stroke()
cr.move_to(clip_over_end_x - 0.5, track_y - 6.5)
cr.line_to(clip_over_end_x - 0.5, track_y + track_height + 6.5)
cr.stroke()
if trim_status != appconsts.ON_BETWEEN_FRAME:
if trim_status == appconsts.ON_FIRST_FRAME:
_draw_end_triangles(cr, selection_frame_x, track_y, track_height, 6)
else:
_draw_end_triangles(cr, selection_frame_x, track_y, track_height, -6)
radius = 5.0
degrees = M_PI/ 180.0
bit = 3
if not trim_mode_in_non_active_state:
cr.set_source_rgb(0.9, 0.9, 0.2)
else:
cr.set_source_rgb(0.2, 0.2, 0.2)
cr.set_line_width(2.0)
cr.move_to(selection_frame_x + radius + bit, track_y + track_height)
cr.arc (selection_frame_x + radius, track_y + track_height - radius, radius, 90 * degrees, 180.0 * degrees)
cr.arc (selection_frame_x + radius, track_y + radius, radius, 180.0 * degrees, 270.0 * degrees)
cr.line_to(selection_frame_x + radius + bit, track_y)
cr.stroke()
cr.move_to(selection_frame_x - radius - bit, track_y)
cr.arc (selection_frame_x - radius, track_y + radius, radius, -90.0 * degrees, 0.0 * degrees)
cr.arc (selection_frame_x - radius, track_y + track_height - radius, radius, 0 * degrees, 90.0 * degrees)
cr.line_to(selection_frame_x - radius - bit, track_y + track_height)
cr.stroke()
def draw_one_roll_overlay(cr, data):
track_height = current_sequence().tracks[data["track"]].height
track_y = _get_track_y(data["track"])
selection_frame_x = _get_frame_x(data["selected_frame"])
trim_limits = data["trim_limits"]
if data["to_side_being_edited"]:
# Case: editing to-clip
first = data["selected_frame"]
last = trim_limits["both_end"] + 1 # +1, end is allowed trim area, we cant clip
x = _get_frame_x(last)
else:
# Case: editing from-clip
first = trim_limits["both_start"] - 1 # -1, start is allowed trim area, we cant clip
last = data["selected_frame"]
x = _get_frame_x(first)
cr.set_line_width(1.0)
cr.set_source_rgb(*OVERLAY_COLOR)
cr.move_to(x, track_y - 6.5)
cr.line_to(x, track_y + track_height + 6.5)
cr.stroke()
cr.set_line_width(2.0)
_draw_trim_clip_overlay(cr, _get_frame_x(first), _get_frame_x(last), track_y, track_height, False, (1,1,1,0.3))
cr.set_source_rgb(*OVERLAY_SELECTION_COLOR)
cr.move_to(selection_frame_x - 0.5, track_y - 6.5)
cr.line_to(selection_frame_x - 0.5, track_y + track_height + 6.5)
cr.stroke()
if trim_status != appconsts.ON_BETWEEN_FRAME:
if trim_status == appconsts.ON_FIRST_FRAME:
_draw_end_triangles(cr, selection_frame_x, track_y, track_height, 6)
else:
_draw_end_triangles(cr, selection_frame_x, track_y, track_height, -6)
radius = 5.0
degrees = M_PI/ 180.0
bit = 3
if not trim_mode_in_non_active_state:
cr.set_source_rgb(0.9, 0.9, 0.2)
else:
cr.set_source_rgb(0.2, 0.2, 0.2)
cr.set_line_width(2.0)
if data["to_side_being_edited"]:
cr.move_to(selection_frame_x + radius + bit, track_y + track_height)
cr.arc (selection_frame_x + radius, track_y + track_height - radius, radius, 90 * degrees, 180.0 * degrees)
cr.arc (selection_frame_x + radius, track_y + radius, radius, 180.0 * degrees, 270.0 * degrees)
cr.line_to(selection_frame_x + radius + bit, track_y)
else:
cr.move_to(selection_frame_x - radius - bit, track_y)
cr.arc (selection_frame_x - radius, track_y + radius, radius, -90.0 * degrees, 0.0 * degrees)
cr.arc (selection_frame_x - radius, track_y + track_height - radius, radius, 0 * degrees, 90.0 * degrees)
cr.line_to(selection_frame_x - radius - bit, track_y + track_height)
cr.stroke()
def draw_slide_overlay(cr, data):
track_height = current_sequence().tracks[data["track"]].height
track_y = _get_track_y(data["track"])
trim_limits = data["trim_limits"]
clip = data["clip"]
clip_start_frame = trim_limits["clip_start"]
clip_end_frame = clip_start_frame + clip.clip_out - clip.clip_in + 1 # +1 to draw after out frame
clip_start_frame_x = _get_frame_x(clip_start_frame)
clip_end_frame_x = _get_frame_x(clip_end_frame)
cr.set_line_width(2.0)
media_start = clip_start_frame - data["mouse_delta"] - clip.clip_in
orig_media_start_frame_x = _get_frame_x(media_start)
orig_media_end_frame_x = _get_frame_x(media_start + trim_limits["media_length"])
_draw_trim_clip_overlay(cr, orig_media_start_frame_x, orig_media_end_frame_x, track_y, track_height, False, (0.65,0.65,0.65, 0.65))
_draw_end_triangles(cr, orig_media_start_frame_x, track_y, track_height, 6)
_draw_end_triangles(cr, orig_media_end_frame_x, track_y, track_height, -6)
cr.set_line_width(2.0)
cr.set_source_rgb(*OVERLAY_SELECTION_COLOR)
orig_clip_start_frame_x = _get_frame_x(clip_start_frame - data["mouse_delta"])
orig_clip_end_frame_x = _get_frame_x(clip_end_frame - data["mouse_delta"])
_draw_trim_clip_overlay(cr, orig_clip_start_frame_x, orig_clip_end_frame_x, track_y, track_height, False, (1,1,1,0.3))
cr.move_to(clip_start_frame_x - 0.5, track_y - 6.5)
cr.line_to(clip_start_frame_x - 0.5, track_y + track_height + 6.5)
cr.stroke()
cr.move_to(clip_end_frame_x - 0.5, track_y - 6.5)
cr.line_to(clip_end_frame_x - 0.5, track_y + track_height + 6.5)
cr.stroke()
radius = 5.0
degrees = M_PI/ 180.0
bit = 3
if not trim_mode_in_non_active_state:
cr.set_source_rgb(0.9, 0.9, 0.2)
else:
cr.set_source_rgb(0.2, 0.2, 0.2)
cr.set_line_width(2.0)
cr.move_to(clip_start_frame_x - radius - bit, track_y)
cr.arc (clip_start_frame_x - radius, track_y + radius, radius, -90.0 * degrees, 0.0 * degrees)
cr.arc (clip_start_frame_x - radius, track_y + track_height - radius, radius, 0 * degrees, 90.0 * degrees)
cr.line_to(clip_start_frame_x - radius - bit, track_y + track_height)
cr.move_to(clip_end_frame_x + radius + bit, track_y + track_height)
cr.arc (clip_end_frame_x + radius, track_y + track_height - radius, radius, 90 * degrees, 180.0 * degrees)
cr.arc (clip_end_frame_x + radius, track_y + radius, radius, 180.0 * degrees, 270.0 * degrees)
cr.line_to(clip_end_frame_x + radius + bit, track_y)
cr.stroke()
if data["start_frame_being_viewed"]:
x = clip_start_frame_x + 4
else:
x = clip_end_frame_x - 16
cr.set_source_pixbuf(VIEW_SIDE_ICON, x, track_y + 4)
cr.paint()
def draw_compositor_move_overlay(cr, data):
# Get data
press_frame = data["press_frame"]
current_frame = data["current_frame"]
clip_in = data["clip_in"]
clip_length = data["clip_length"]
y = data["compositor_y"]
compositor = data["compositor"]
draw_start = clip_in + (current_frame - press_frame)
clip_start_frame = draw_start - pos
scale_length = clip_length * pix_per_frame
scale_in = clip_start_frame * pix_per_frame
target_track = current_sequence().tracks[compositor.transition.a_track]
target_y = _get_track_y(target_track.id) + target_track.height - COMPOSITOR_HEIGHT_OFF
_create_compositor_cairo_path(cr, scale_in, scale_length, y, target_y)
cr.set_line_width(2.0)
cr.set_source_rgb(*OVERLAY_COLOR)
cr.stroke()
def draw_compositor_trim(cr, data):
clip_in = data["clip_in"]
clip_out = data["clip_out"]
y = data["compositor_y"]
compositor = data["compositor"]
clip_start_frame = clip_in - pos
clip_length = clip_out - clip_in + 1
scale_length = clip_length * pix_per_frame
scale_in = clip_start_frame * pix_per_frame
target_track = current_sequence().tracks[compositor.transition.a_track]
target_y = _get_track_y(target_track.id) + target_track.height - COMPOSITOR_HEIGHT_OFF
_create_compositor_cairo_path(cr, scale_in, scale_length, y, target_y)
cr.set_line_width(2.0)
cr.set_source_rgb(*OVERLAY_COLOR)
cr.stroke()
if data["trim_is_clip_in"] == True:
x = scale_in + 2
else:
x = scale_in + scale_length - 26
_draw_two_arrows(cr, x, y + 4, 4)
def _create_compositor_cairo_path(cr, scale_in, scale_length, y, target_y):
cr.move_to(scale_in + 0.5, y + 0.5)
cr.line_to(scale_in + 0.5 + scale_length, y + 0.5)
cr.line_to(scale_in + 0.5 + scale_length, y + 0.5 + COMPOSITOR_HEIGHT)
cr.line_to(scale_in + 0.5 + COMPOSITOR_TRACK_X_PAD + 2 * COMPOSITOR_TRACK_ARROW_WIDTH, y + 0.5 + COMPOSITOR_HEIGHT)
cr.line_to(scale_in + 0.5 + COMPOSITOR_TRACK_X_PAD + 2 * COMPOSITOR_TRACK_ARROW_WIDTH, target_y + 0.5 - COMPOSITOR_TRACK_ARROW_HEAD_WIDTH_HEIGHT)
cr.line_to(scale_in + 0.5 + COMPOSITOR_TRACK_X_PAD + COMPOSITOR_TRACK_ARROW_WIDTH + COMPOSITOR_TRACK_ARROW_HEAD_WIDTH, target_y + 0.5 - COMPOSITOR_TRACK_ARROW_HEAD_WIDTH_HEIGHT)
cr.line_to(scale_in + 0.5 + COMPOSITOR_TRACK_X_PAD + COMPOSITOR_TRACK_ARROW_WIDTH, target_y + 0.5)
cr.line_to(scale_in + 0.5 + COMPOSITOR_TRACK_X_PAD + COMPOSITOR_TRACK_ARROW_WIDTH - COMPOSITOR_TRACK_ARROW_HEAD_WIDTH, target_y + 0.5 - COMPOSITOR_TRACK_ARROW_HEAD_WIDTH_HEIGHT)
cr.line_to(scale_in + 0.5 + COMPOSITOR_TRACK_X_PAD, target_y + 0.5 - COMPOSITOR_TRACK_ARROW_HEAD_WIDTH_HEIGHT)
cr.line_to(scale_in + 0.5 + COMPOSITOR_TRACK_X_PAD, y + 0.5 + COMPOSITOR_HEIGHT)
cr.line_to(scale_in + 0.5, y + 0.5 + COMPOSITOR_HEIGHT)
cr.close_path()
def _draw_two_arrows(cr, x, y, distance):
"""
Draws two arrows indicating that user can drag in
both directions in a trim mode
"""
cr.set_source_rgb(*OVERLAY_COLOR)
cr.move_to(x + 10, y)
cr.line_to(x + 10, y + 10)
cr.line_to(x, y + 5)
cr.close_path()
cr.fill()
cr.move_to(x + 10 + distance, y)
cr.line_to(x + 10 + distance, y + 10)
cr.line_to(x + 20 + distance, y + 5)
cr.close_path()
cr.fill()
def _draw_selected_frame(cr, x, y, track_height):
cr.set_source_rgb(*OVERLAY_SELECTION_COLOR)
cr.move_to(x - 0.5, y - 3.5)
cr.line_to(x - 0.5, y + track_height + 3.5)
cr.stroke()
def _draw_mode_arrow(cr, x, y, color):
cr.move_to(x - 3.5, y - 3.5)
cr.line_to(x + 3.5, y - 3.5)
cr.line_to(x + 3.5, y + 8.5)
cr.line_to(x + 5.5, y + 8.5)
cr.line_to(x, y + 12.5)
cr.line_to(x - 5.5, y + 8.5)
cr.line_to(x - 3.5, y + 8.5)
cr.close_path()
cr.set_source_rgb(*color)
cr.fill_preserve()
cr.set_source_rgb(0, 0, 0)
cr.set_line_width(2.0)
cr.stroke()
def _draw_end_triangles(cr, x, y, h, direction):
triangles = 4
if h < appconsts.TRACK_HEIGHT_NORMAL:
triangles = 2
cr.set_source_rgb(1, 1, 1)
for i in range(0, triangles):
cr.move_to(x, y + 2.5)
cr.line_to(x + direction, y + 7.0)
cr.line_to(x, y + 11.5)
cr.close_path()
cr.fill()
y = y + 12.0
def _draw_trim_clip_overlay(cr, start_x, end_x, y, track_height, draw_stroke, color=(1,1,1,1)):
cr.set_source_rgba(*color)
cr.rectangle(start_x, y, end_x - start_x, track_height)
if draw_stroke:
cr.stroke()
else:
cr.fill()
def _draw_overwrite_clips_overlay(cr, start_x, end_x, y, track_height):
cr.set_source_rgba(*OVERWRITE_OVERLAY_COLOR)
cr.rectangle(start_x, y, end_x - start_x, track_height)
cr.fill()
def _draw_view_icon(cr, x, y):
cr.set_source_pixbuf(VIEW_SIDE_ICON, x, y)
cr.paint()
# ------------------------------- WIDGETS
class TimeLineCanvas:
"""
GUI component for editing clips.
"""
def __init__(self, press_listener, move_listener, release_listener, double_click_listener,
mouse_scroll_listener, leave_notify_listener, enter_notify_listener):
# Create widget and connect listeners
self.widget = CairoDrawableArea(WIDTH,
HEIGHT,
self._draw)
self.widget.press_func = self._press_event
self.widget.motion_notify_func = self._motion_notify_event
self.widget.release_func = self._release_event
self.widget.mouse_scroll_func = mouse_scroll_listener
#self.widget.set_events(self.widget.get_events() | gtk.gdk.POINTER_MOTION_MASK)
# Mouse events are passed on
self.press_listener = press_listener
self.move_listener = move_listener
self.release_listener = release_listener
self.double_click_listener = double_click_listener
self.widget.leave_notify_func = leave_notify_listener
self.widget.enter_notify_func = enter_notify_listener
# Edit mode
self.edit_mode_data = None
self.edit_mode_overlay_draw_func = draw_insert_overlay
# Drag state
self.drag_on = False
# for edit mode setting
global canvas_widget
canvas_widget = self
#---------------------------- MOUSE EVENTS
def _press_event(self, event):
"""
Mouse button callback
"""
if event.type == gtk.gdk._2BUTTON_PRESS:
self.double_click_listener(get_frame(event.x), event.x, event.y)
return
self.drag_on = True
self.press_listener(event, get_frame(event.x))
def _motion_notify_event(self, x, y, state):
"""
Mouse move callback
"""
if not self.drag_on:
self.set_pointer_context(x, y)
return
button = -1
if (state & gtk.gdk.BUTTON1_MASK):
button = 1
elif (state & gtk.gdk.BUTTON3_MASK):
button = 3
self.move_listener(x, y, get_frame(x), button, state)
def _release_event(self, event):
"""
Mouse release callback.
"""
self.drag_on = False
self.release_listener(event.x, event.y, get_frame(event.x), \
event.button, event.state)
def set_pointer_context(self, x, y):
frame = get_frame(x)
hit_compositor = compositor_hit(frame, y, current_sequence().compositors)
if hit_compositor != None:
print "comp"
return
track = get_track(y)
if track == None:
return
clip_index = current_sequence().get_clip_index(track, frame)
if clip_index == -1:
return
clip_start_frame = track.clip_start(clip_index) - pos
if abs(x - _get_frame_x(clip_start_frame)) < 5:
print "clip start"
return
clip_end_frame = track.clip_start(clip_index + 1) - pos
if abs(x - _get_frame_x(clip_end_frame)) < 5:
print "clip end"
return
#----------------------------------------- DRAW
def _draw(self, event, cr, allocation):
x, y, w, h = allocation
# Draw bg
cr.set_source_rgb(*BG_COLOR)
cr.rectangle(0, 0, w, h)
cr.fill()
# This can get called during loads by unwanted expose events
if editorstate.project_is_loading == True:
return
# Init sync draw structures
self.parent_positions = {}
self.sync_children = []
# Draw tracks
for i in range(1, len(current_sequence().tracks) - 1): # black and hidden tracks are ignored
self.draw_track(cr
,current_sequence().tracks[i]
,_get_track_y(i)
,w)
self.draw_compositors(cr)
self.draw_sync_relations(cr)
# Exit displaying from fake_current_pointer for SLIDE_TRIM mode if last displayed
# was from fake_pointer but this is not anymore
global fake_current_frame
if EDIT_MODE() != editorstate.SLIDE_TRIM and fake_current_frame != None:
PLAYER().seek_frame(fake_current_frame)
fake_current_frame = None
# Draw frame pointer
if EDIT_MODE() != editorstate.SLIDE_TRIM or PLAYER().looping():
current_frame = PLAYER().tracktor_producer.frame()
else:
current_frame = fake_current_frame
if timeline_visible():
pointer_frame = current_frame
cr.set_source_rgb(0, 0, 0)
else:
pointer_frame = editorstate.tline_shadow_frame
cr.set_source_rgb(*SHADOW_POINTER_COLOR)
disp_frame = pointer_frame - pos
frame_x = math.floor(disp_frame * pix_per_frame) + 0.5
cr.move_to(frame_x, 0)
cr.line_to(frame_x, h)
cr.set_line_width(1.0)
cr.stroke()
# Draw edit mode overlay
if self.edit_mode_overlay_draw_func != None:
self.edit_mode_overlay_draw_func(cr,self.edit_mode_data)
def draw_track(self, cr, track, y, width):
"""
Draws visible clips in track.
"""
# Get text pos for track height
track_height = track.height
if track_height == sequence.TRACK_HEIGHT_NORMAL:
text_y = TEXT_Y
else:
text_y = TEXT_Y_SMALL
# Get clip indexes for clips overlapping first and last displayed frame.
start = track.get_clip_index_at(int(pos))
end = track.get_clip_index_at(int(pos + width / pix_per_frame))
width_frames = float(width) / pix_per_frame
# Add 1 to end because range() last index exclusive
# MLT returns clips structure size + 1 if frame after last clip,
# so in that case don't add anything.
if len(track.clips) != end:
end = end + 1
# Get frame of clip.clip_in_in on timeline.
clip_start_in_tline = track.clip_start(start)
# Pos is the first drawn frame.
# clip_start_frame starts always less or equal to zero as this is
# the first maybe partially displayed clip.
clip_start_frame = clip_start_in_tline - pos
# Check if we need to collect positions for drawing sync relations
collect_positions = False
if track.id == current_sequence().first_video_index:
collect_positions = True
proxy_paths = current_proxy_media_paths()
# Draw clips in draw range
for i in range(start, end):
clip = track.clips[i]
# Get clip frame values
clip_in = clip.clip_in
clip_out = clip.clip_out
clip_length = clip_out - clip_in + 1 # +1 because in and out both inclusive
scale_length = clip_length * pix_per_frame
scale_in = clip_start_frame * pix_per_frame
# Collect positions for drawing sync relations
if collect_positions:
self.parent_positions[clip.id] = scale_in
# Fill clip bg
if scale_length > FILL_MIN:
# Select color
clip_bg_col = None
if clip.color != None:
cr.set_source_rgb(*clip.color)
clip_bg_col = clip.color
elif clip.is_blanck_clip:
if clip.selected:
grad = cairo.LinearGradient (0, y, 0, y + track_height)
grad.add_color_stop_rgba(*BLANK_CLIP_COLOR_SELECTED_GRAD)
grad.add_color_stop_rgba(*BLANK_CLIP_COLOR_SELECTED_GRAD_L)
cr.set_source(grad)
else:
grad = cairo.LinearGradient (0, y, 0, y + track_height)
grad.add_color_stop_rgba(*BLANK_CLIP_COLOR_GRAD)
grad.add_color_stop_rgba(*BLANK_CLIP_COLOR_GRAD_L)
cr.set_source(grad)
elif track.type == sequence.VIDEO:
if clip.media_type == sequence.VIDEO:
if not clip.selected:
grad = cairo.LinearGradient (0, y, 0, y + track_height)
grad.add_color_stop_rgba(*CLIP_COLOR_GRAD)
grad.add_color_stop_rgba(*CLIP_COLOR_GRAD_L)
clip_bg_col = CLIP_COLOR_GRAD[1:4]
cr.set_source(grad)
else:
cr.set_source_rgb(*CLIP_SELECTED_COLOR)
clip_bg_col = CLIP_SELECTED_COLOR
else: # IMAGE type
if not clip.selected:
grad = cairo.LinearGradient (0, y, 0, y + track_height)
grad.add_color_stop_rgba(*IMAGE_CLIP_COLOR_GRAD)
grad.add_color_stop_rgba(*IMAGE_CLIP_COLOR_GRAD_L)
clip_bg_col = IMAGE_CLIP_COLOR_GRAD[1:4]
cr.set_source(grad)
else:
cr.set_source_rgb(*IMAGE_CLIP_SELECTED_COLOR)
clip_bg_col = IMAGE_CLIP_SELECTED_COLOR
else:
if not clip.selected:
grad = cairo.LinearGradient (0, y, 0, y + track_height)
grad.add_color_stop_rgba(*AUDIO_CLIP_COLOR_GRAD)
grad.add_color_stop_rgba(*AUDIO_CLIP_COLOR_GRAD_L)
clip_bg_col = AUDIO_CLIP_COLOR_GRAD[1:4]
cr.set_source(grad)
else:
clip_bg_col = AUDIO_CLIP_SELECTED_COLOR
cr.set_source_rgb(*AUDIO_CLIP_SELECTED_COLOR)
# Clip bg
cr.rectangle(scale_in, y, scale_length, track_height)
cr.fill()
# Draw transition clip image
if ((scale_length > FILL_MIN) and hasattr(clip, "rendered_type")):
if not clip.selected:
cr.set_source_rgb(1.0, 1.0, 1.0)
else:
cr.set_source_rgb(*SINGLE_TRACK_TRANSITION_SELECTED)
cr.rectangle(scale_in + 2.5,
y + 2.5, scale_length - 4.0,
track_height - 4.0)
cr.fill()
right = scale_in + 2.5 + scale_length - 6.0
right_half = scale_in + 2.5 + ((scale_length - 6.0) / 2.0)
down = y + 2.5 + track_height - 6.0
down_half = y + 2.5 + ((track_height - 6.0) / 2.0)
cr.set_source_rgb(0, 0, 0)
if clip.rendered_type == appconsts.RENDERED_DISSOLVE:
cr.move_to(right, y + 4.5)
cr.line_to(right, down)
cr.line_to(scale_in + 4.5, down)
cr.close_path()
cr.fill()
elif clip.rendered_type == appconsts.RENDERED_WIPE:
cr.rectangle(scale_in + 2.0, y + 2.0, scale_length - 4.0, track_height - 4.0)
cr.fill()
if not clip.selected:
cr.set_source_rgb(1.0, 1.0, 1.0)
else:
cr.set_source_rgb(*SINGLE_TRACK_TRANSITION_SELECTED)
cr.move_to(right_half, y + 3.0 + 2.0)
cr.line_to(right - 2.0, down_half)
cr.line_to(right_half, down - 2.0)
cr.line_to(scale_in + 2.0 + 4.0, down_half)
cr.close_path()
cr.fill()
elif clip.rendered_type == appconsts.RENDERED_COLOR_DIP:
cr.move_to(scale_in + 4.5, y + 4.5)
cr.line_to(right, y + 4.5)
cr.line_to(right_half, down)
cr.close_path()
cr.fill()
elif clip.rendered_type == appconsts.RENDERED_FADE_IN:
cr.move_to(scale_in + 4.5, y + 4.5)
cr.line_to(right, y + 4.5)
cr.line_to(scale_in + 4.5, down_half)
cr.close_path()
cr.fill()
cr.move_to(scale_in + 4.5, down_half)
cr.line_to(right, down)
cr.line_to(scale_in + 4.5, down)
cr.close_path()
cr.fill()
else: # clip.rendered_type == appconsts.RENDERED_FADE_OUT:
cr.move_to(scale_in + 4.5, y + 4.5)
cr.line_to(right, y + 4.5)
cr.line_to(right, down_half)
cr.close_path()
cr.fill()
cr.move_to(right, down_half)
cr.line_to(right, down)
cr.line_to(scale_in + 4.5, down)
cr.close_path()
cr.fill()
# Draw sync stripe
if scale_length > FILL_MIN:
if clip.sync_data != None:
stripe_color = SYNC_OK_COLOR
if clip.sync_data.sync_state == appconsts.SYNC_CORRECT:
stripe_color = SYNC_OK_COLOR
elif clip.sync_data.sync_state == appconsts.SYNC_OFF:
stripe_color = SYNC_OFF_COLOR
else:
stripe_color = SYNC_GONE_COLOR
dx = scale_in + 1
dy = y + track_height - SYNC_STRIPE_HEIGHT
saw_points = []
saw_points.append((dx, dy))
saw_delta = SYNC_SAW_HEIGHT
for i in range(0, int((scale_length - 2) / SYNC_SAW_WIDTH) + 1):
dx += SYNC_SAW_WIDTH
dy += saw_delta
saw_points.append((dx, dy))
saw_delta = -(saw_delta)
px = scale_in + 1 + scale_length - 2
py = y + track_height
cr.move_to(px, py)
for p in reversed(saw_points):
cr.line_to(*p)
cr.line_to(scale_in + 1, y + track_height)
cr.close_path()
cr.set_source_rgb(*stripe_color)
cr.fill_preserve()
cr.set_source_rgb(0.3, 0.3, 0.3)
cr.stroke()
if clip.sync_data.sync_state != appconsts.SYNC_CORRECT:
cr.set_source_rgb(1, 1, 1)
cr.select_font_face ("sans-serif",
cairo.FONT_SLANT_NORMAL,
cairo.FONT_WEIGHT_NORMAL)
cr.set_font_size(9)
cr.move_to(scale_in + TEXT_X, y + track_height - 2)
try: # This is needed for backwards compability
# Projects saved before adding this feature do not have sync_diff attribute
cr.show_text(str(clip.sync_diff))
except:
clip.sync_diff = "n/a"
cr.show_text(str(clip.sync_diff))
# Draw proxy indicator
if scale_length > FILL_MIN:
if (not clip.is_blanck_clip) and proxy_paths.get(clip.path) != None:
cr.set_source_rgb(*PROXY_STRIP_COLOR)
cr.rectangle(scale_in, y, scale_length, 8)
cr.fill()
# Draw clip frame
cr.set_line_width(1.0)
if scale_length > FILL_MIN:
cr.set_source_rgb(0, 0, 0)
else:
cr.set_source_rgb(0.3, 0.3, 0.3)
cr.rectangle(scale_in + 0.5,
y + 0.5, scale_length,
track_height)
cr.stroke()
# No further drawing for blank clips
if clip.is_blanck_clip:
clip_start_frame += clip_length
continue
# Save sync children data
if clip.sync_data != None:
self.sync_children.append((clip, track, scale_in))
# Draw audio level data
if clip.waveform_data != None and scale_length > FILL_MIN:
r, g, b = clip_bg_col
cr.set_source_rgb(r * 0.7, g * 0.7, b * 0.7)
# Get level bar height and position for track height
if track.height == sequence.TRACK_HEIGHT_NORMAL:
y_pad = WAVEFORM_PAD_LARGE
bar_height = 40.0
else:
y_pad = WAVEFORM_PAD_SMALL
bar_height = 20.0
# Draw all frames only if pixels per frame > 2, otherwise
# draw only every other or fewer frames
draw_pix_per_frame = pix_per_frame
if draw_pix_per_frame < 2:
draw_pix_per_frame = 2
step = int(2 / pix_per_frame)
if step < 1:
step = 1
else:
step = 1
# Draw only frames in display
draw_first = clip_in
draw_last = clip_out + 1
if clip_start_frame < 0:
draw_first = int(draw_first - clip_start_frame)
if draw_first + width_frames < draw_last:
draw_last = int(draw_first + width_frames) + 1
# Get media frame 0 position in screen pixels
media_start_pos_pix = scale_in - clip_in * pix_per_frame
# Draw level bar for each frame in draw range
for i in range(draw_first, draw_last, step):
x = media_start_pos_pix + i * pix_per_frame
h = bar_height * clip.waveform_data[i]
if h < 1:
h = 1
cr.rectangle(x, y + y_pad + (bar_height - h), draw_pix_per_frame, h)
cr.fill()
# Emboss
if scale_length > EMBOSS_MIN:
# Corner points
left = scale_in + 1.5
up = y + 1.5
right = left + scale_length - 2.0
down = up + track_height - 2.0
# Draw lines
cr.set_source_rgb(0.75, 0.43, 0.79)
cr.move_to(left, down)
cr.line_to(left, up)
cr.stroke()
cr.move_to(left, up)
cr.line_to(right, up)
cr.stroke()
cr.set_source_rgb(0.47, 0.28, 0.51)
cr.move_to(right, up)
cr.line_to(right, down)
cr.stroke()
cr.move_to(right, down)
cr.line_to(left, down)
cr.stroke()
# Draw text and filter, sync icons
if scale_length > TEXT_MIN:
if not hasattr(clip, "rendered_type"):
# Text
cr.set_source_rgb(0, 0, 0)
cr.select_font_face ("sans-serif",
cairo.FONT_SLANT_NORMAL,
cairo.FONT_WEIGHT_NORMAL)
cr.set_font_size(11)
cr.move_to(scale_in + TEXT_X, y + text_y)
cr.show_text(clip.name.upper())
icon_slot = 0
# Filter icon
if len(clip.filters) > 0:
ix, iy = ICON_SLOTS[icon_slot]
cr.set_source_pixbuf(FILTER_CLIP_ICON, int(scale_in) + int(scale_length) - ix, y + iy)
cr.paint()
icon_slot = icon_slot + 1
# Mute icon
if clip.mute_filter != None:
icon = AUDIO_MUTE_ICON
ix, iy = ICON_SLOTS[icon_slot]
cr.set_source_pixbuf(icon, int(scale_in) + int(scale_length) - ix, y + iy)
cr.paint()
icon_slot = icon_slot + 1
if clip == clipeffectseditor.clip:
icon = EDIT_INDICATOR
ix = int(scale_in) + int(scale_length) / 2 - 7
iy = y + int(track_height) / 2 - 7
cr.set_source_pixbuf(icon, ix, iy)
cr.paint()
# Draw sync offset value
if scale_length > FILL_MIN:
if clip.sync_data != None:
if clip.sync_data.sync_state != appconsts.SYNC_CORRECT:
cr.set_source_rgb(1, 1, 1)
cr.select_font_face ("sans-serif",
cairo.FONT_SLANT_NORMAL,
cairo.FONT_WEIGHT_NORMAL)
cr.set_font_size(9)
cr.move_to(scale_in + TEXT_X, y + track_height - 2)
cr.show_text(str(clip.sync_diff))
# Get next draw position
clip_start_frame += clip_length
# Fill rest of track with bg color if needed
scale_in = clip_start_frame * pix_per_frame
if scale_in < width:
cr.rectangle(scale_in + 0.5, y, width - scale_in, track_height)
cr.set_source_rgb(*BG_COLOR)
cr.fill()
def draw_compositors(self, cr):
compositors = current_sequence().get_compositors()
for comp in compositors:
# compositor clip and edge
track = current_sequence().tracks[comp.transition.b_track]
target_track = current_sequence().tracks[comp.transition.a_track]
y = _get_track_y(track.id) + track.height - COMPOSITOR_HEIGHT_OFF
target_y = _get_track_y(target_track.id) + target_track.height - COMPOSITOR_HEIGHT_OFF
scale_in = (comp.clip_in - pos) * pix_per_frame
scale_length = (comp.clip_out - comp.clip_in + 1) * pix_per_frame # +1, out inclusive
if comp.selected == False:
color = COMPOSITOR_CLIP
else:
color = COMPOSITOR_CLIP_SELECTED
cr.set_source_rgba(*color)
_create_compositor_cairo_path(cr, scale_in, scale_length, y, target_y)
cr.fill_preserve()
cr.set_source_rgb(0, 0, 0)
cr.set_line_width(1.0)
cr.stroke()
# text
cr.save()
cr.rectangle(scale_in + 0.5,
y + 0.5, scale_length,
COMPOSITOR_HEIGHT)
cr.clip()
cr.new_path()
cr.set_source_rgb(1, 1, 1)
cr.select_font_face ("sans-serif",
cairo.FONT_SLANT_NORMAL,
cairo.FONT_WEIGHT_NORMAL)
cr.set_font_size(11)
cr.move_to(scale_in + COMPOSITOR_TEXT_X, y + COMPOSITOR_TEXT_Y)
cr.show_text(comp.name.upper())
cr.restore()
def draw_sync_relations(self, cr):
parent_y = _get_track_y(current_sequence().first_video_index)
radius = 4
small_radius = 2
pad = 6
degrees = M_PI / 180.0
for child_data in self.sync_children:
child_clip, track, child_x = child_data
child_y = _get_track_y(track.id)
try:
parent_x = self.parent_positions[child_clip.sync_data.master_clip.id]
except KeyError: # parent clip not in tline view, don't draw - think about another solution
continue
cr.set_line_width(2.0)
cr.set_source_rgb(0.1, 0.1, 0.1)
cr.move_to(child_x + pad, child_y + pad)
cr.line_to(parent_x + pad, parent_y + pad)
cr.stroke()
cr.move_to(child_x + pad, child_y + pad)
cr.arc (child_x + pad, child_y + pad, radius, 0.0 * degrees, 360.0 * degrees)
cr.fill()
cr.set_source_rgb(0.9, 0.9, 0.9)
cr.move_to(child_x + pad, child_y + pad)
cr.arc (child_x + pad, child_y + pad, small_radius, 0.0 * degrees, 360.0 * degrees)
cr.fill()
cr.set_source_rgb(0.1, 0.1, 0.1)
cr.move_to(parent_x + pad, parent_y + pad)
cr.arc(parent_x + pad, parent_y + pad, radius, 0.0 * degrees, 360.0 * degrees)
cr.fill()
cr.set_source_rgb(0.9, 0.9, 0.9)
cr.move_to(parent_x + pad, parent_y + pad)
cr.arc(parent_x + pad, parent_y + pad, small_radius, 0.0 * degrees, 360.0 * degrees)
cr.fill()
class TimeLineColumn:
"""
GUI component for displaying and editing track parameters.
"""
def __init__(self, active_listener, center_listener):
# Init widget
self.widget = CairoDrawableArea(COLUMN_WIDTH,
HEIGHT,
self._draw)
self.widget.press_func = self._press_event
self.active_listener = active_listener
self.center_listener = center_listener
self.init_listeners()
# ------------------------------- MOUSE EVENTS
def init_listeners(self):
self.track_testers = []
# Add track click testers
# track zero is ignored black bg track
for i in range(1, len(current_sequence().tracks) - 1): # black and hidden tracks are ignored
start = _get_track_y(i)
end = start + current_sequence().tracks[i].height
tester = ValueTester(start, end, self.track_hit)
tester.data.track = i
self.track_testers.append(tester)
# Add switch click testers
self.switch_testers = []
# Active area tester
center_width = COLUMN_WIDTH - COLUMN_LEFT_PAD - ACTIVE_SWITCH_WIDTH
tester = ValueTester(COLUMN_LEFT_PAD + center_width, COLUMN_WIDTH,
self.active_listener)
self.switch_testers.append(tester)
# Center area tester
tester = ValueTester(COLUMN_LEFT_PAD, COLUMN_WIDTH - ACTIVE_SWITCH_WIDTH,
self.center_listener)
self.switch_testers.append(tester)
def _press_event(self, event):
"""
Mouse button callback
"""
self.event = event
for tester in self.track_testers:
tester.data.x = event.x # pack x value to go
tester.data.event = event
tester.call_listener_if_hit(event.y)
def track_hit(self, data):
"""
Called when a track has been hit.
Call appropriate switch press listener, mute or active switch
"""
for tester in self.switch_testers:
tester.data.track = data.track # pack track index to go
tester.data.event = data.event
tester.call_listener_if_hit(data.x)
# --------------------------------------------- DRAW
def _draw(self, event, cr, allocation):
x, y, w, h = allocation
# Draw bg
cr.set_source_rgb(*BG_COLOR)
cr.rectangle(0, 0, w, h)
cr.fill()
# get insert track
insert_track_index = current_sequence().get_first_active_track().id
# Draw tracks
for i in range(1, len(current_sequence().tracks) - 1):
y = _get_track_y(i)
is_insert_track = (insert_track_index==i)
self.draw_track(cr, current_sequence().tracks[i], y, is_insert_track)
def draw_track(self, cr, track, y, is_insert_track):
# Draw center area
center_width = COLUMN_WIDTH - COLUMN_LEFT_PAD - ACTIVE_SWITCH_WIDTH
rect = (COLUMN_LEFT_PAD, y, center_width, track.height)
grad = cairo.LinearGradient (COLUMN_LEFT_PAD, y, COLUMN_LEFT_PAD, y + track.height)
self._add_gradient_color_stops(grad, track)
cr.rectangle(*rect)
cr.set_source(grad)
cr.fill()
self.draw_edge(cr, rect)
# Draw active switch bg end edge
rect = (COLUMN_LEFT_PAD + center_width - 1, y, ACTIVE_SWITCH_WIDTH + 1, track.height)
cr.rectangle(*rect)
if track.active:
grad = cairo.LinearGradient(COLUMN_LEFT_PAD + center_width, y,
COLUMN_LEFT_PAD + center_width, y + track.height)
self._add_gradient_color_stops(grad, track)
cr.set_source(grad)
else:
cr.set_source_rgb(*COLUMN_NOT_ACTIVE_COLOR)
cr.fill()
self.draw_edge(cr, rect)
# Draw type and index text
pango_context = pangocairo.CairoContext(cr)
layout = pango_context.create_layout()
text = utils.get_track_name(track, current_sequence())
layout.set_text(text)
desc = pango.FontDescription("Sans Bold 11")
layout.set_font_description(desc)
pango_context.set_source_rgb(0.0, 0.0, 0)
if track.height == sequence.TRACK_HEIGHT_NORMAL:
text_y = ID_PAD_Y
else:
text_y = ID_PAD_Y_SMALL
pango_context.move_to(COLUMN_LEFT_PAD + ID_PAD_X, y + text_y)
pango_context.update_layout(layout)
pango_context.show_layout(layout)
# Draw mute icon
mute_icon = None
if track.mute_state == appconsts.TRACK_MUTE_VIDEO and track.type == appconsts.VIDEO:
mute_icon = MUTE_VIDEO_ICON
elif track.mute_state == appconsts.TRACK_MUTE_AUDIO and track.type == appconsts.VIDEO:
mute_icon = MUTE_AUDIO_ICON
elif track.mute_state == appconsts.TRACK_MUTE_ALL and track.type == appconsts.AUDIO:
mute_icon = MUTE_AUDIO_A_ICON
elif track.mute_state == appconsts.TRACK_MUTE_ALL:
mute_icon = MUTE_ALL_ICON
elif track.type == appconsts.VIDEO:
mute_icon = TRACK_ALL_ON_V_ICON
else:
mute_icon = TRACK_ALL_ON_A_ICON
if mute_icon != None:
ix, iy = MUTE_ICON_POS
if track.height > sequence.TRACK_HEIGHT_SMALL:
ix, iy = MUTE_ICON_POS_NORMAL
cr.set_source_pixbuf(mute_icon, ix, y + iy)
cr.paint()
# Draw locked icon
if track.edit_freedom == sequence.LOCKED:
ix, iy = LOCK_POS
cr.set_source_pixbuf(FULL_LOCK_ICON, ix, y + iy)
cr.paint()
# Draw insert arrow
if is_insert_track == True:
ix, iy = INSRT_ICON_POS
if track.height == sequence.TRACK_HEIGHT_SMALL:
ix, iy = INSRT_ICON_POS_SMALL
cr.set_source_pixbuf(INSERT_ARROW_ICON, ix, y + iy)
cr.paint()
def _add_gradient_color_stops(self, grad, track):
if track.id == current_sequence().first_video_index:
grad.add_color_stop_rgba(*TRACK_GRAD_ORANGE_STOP1)
grad.add_color_stop_rgba(*TRACK_GRAD_ORANGE_STOP3)
else:
grad.add_color_stop_rgba(*TRACK_GRAD_STOP1)
grad.add_color_stop_rgba(*TRACK_GRAD_STOP3)
def draw_edge(self, cr, rect):
cr.set_line_width(1.0)
cr.set_source_rgb(0, 0, 0)
cr.rectangle(rect[0] + 0.5, rect[1] + 0.5, rect[2] - 1, rect[3])
cr.stroke()
class TimeLineFrameScale:
"""
GUI component for displaying frame tme value scale.
"""
def __init__(self, set_default_callback, mouse_scroll_listener):
self.widget = CairoDrawableArea(WIDTH,
SCALE_HEIGHT,
self._draw)
self.widget.press_func = self._press_event
self.widget.motion_notify_func = self._motion_notify_event
self.widget.release_func = self._release_event
self.widget.mouse_scroll_func = mouse_scroll_listener
self.drag_on = False
self.set_default_callback = set_default_callback
if editorpersistance.prefs.dark_theme == True:
global FRAME_SCALE_SELECTED_COLOR_GRAD, FRAME_SCALE_SELECTED_COLOR_GRAD_L
FRAME_SCALE_SELECTED_COLOR_GRAD = DARK_FRAME_SCALE_SELECTED_COLOR_GRAD
FRAME_SCALE_SELECTED_COLOR_GRAD_L = DARK_FRAME_SCALE_SELECTED_COLOR_GRAD_L
def _press_event(self, event):
if event.button == 1 or event.button == 3:
if not timeline_visible():
updater.display_sequence_in_monitor()
return
trimmodes.set_no_edit_trim_mode()
frame = current_sequence().get_seq_range_frame(get_frame(event.x))
PLAYER().seek_frame(frame)
self.drag_on = True
def _motion_notify_event(self, x, y, state):
if((state & gtk.gdk.BUTTON1_MASK)
or(state & gtk.gdk.BUTTON3_MASK)):
if self.drag_on:
frame = current_sequence().get_seq_range_frame(get_frame(x))
PLAYER().seek_frame(frame)
def _release_event(self, event):
if self.drag_on:
frame = current_sequence().get_seq_range_frame(get_frame(event.x))
PLAYER().seek_frame(frame)
self.drag_on = False
# --------------------------------------------- DRAW
def _draw(self, event, cr, allocation):
"""
Callback for repaint from CairoDrawableArea.
We get cairo contect and allocation.
"""
x, y, w, h = allocation
# Draw grad bg
grad = cairo.LinearGradient (0, 0, 0, h)
grad.add_color_stop_rgba(*FRAME_SCALE_COLOR_GRAD)
grad.add_color_stop_rgba(*FRAME_SCALE_COLOR_GRAD_L)
cr.set_source(grad)
cr.rectangle(0,0,w,h)
cr.fill()
# This can get called during loads by unwanted expose events
if editorstate.project_is_loading == True:
return
# Get sequence and frames per second value
seq = current_sequence()
fps = seq.profile.fps()
# Selected range
if seq.tractor.mark_in != -1 and seq.tractor.mark_out != -1:
in_x = (seq.tractor.mark_in - pos) * pix_per_frame
out_x = (seq.tractor.mark_out + 1 - pos) * pix_per_frame
grad = cairo.LinearGradient (0, 0, 0, h)
grad.add_color_stop_rgba(*FRAME_SCALE_SELECTED_COLOR_GRAD)
cr.set_source(grad)
cr.rectangle(in_x,0,out_x-in_x,h)
cr.fill()
# Set line attr for frames lines
cr.set_source_rgb(*FRAME_SCALE_LINES)
cr.set_line_width(1.0)
big_tick_step = -1 # this isn't rendered most ranges, -1 is flag
# Get displayed frame range
view_start_frame = pos
view_end_frame = int(pos + w / pix_per_frame)
# Get draw steps for marks and tc texts
if pix_per_frame > DRAW_THRESHOLD_1:
small_tick_step = 1
big_tick_step = fps / 2
tc_draw_step = fps / 2
elif pix_per_frame > DRAW_THRESHOLD_2:
small_tick_step = fps
tc_draw_step = fps
elif pix_per_frame > DRAW_THRESHOLD_3:
small_tick_step = fps * 2
tc_draw_step = fps * 2
elif pix_per_frame > DRAW_THRESHOLD_4:
small_tick_step = fps * 3
tc_draw_step = fps * 3
else:
view_length = view_end_frame - view_start_frame
small_tick_step = int(view_length / NUMBER_OF_LINES)
tc_draw_step = int(view_length / NUMBER_OF_LINES)
# Draw small tick lines
# Get draw range in steps from 0
start = int(view_start_frame / small_tick_step)
if start * small_tick_step == pos:
start += 1 # don't draw line on first pixel of scale display
# +1 to ensure coverage
end = int(view_end_frame / small_tick_step) + 1
for i in range(start, end):
x = math.floor(i * small_tick_step * pix_per_frame - pos * pix_per_frame) + 0.5
cr.move_to(x, SCALE_HEIGHT)
cr.line_to(x, SMALL_TICK_Y)
cr.stroke()
# Draw big tick lines, if required
if big_tick_step != -1:
count = int(seq.get_length() / big_tick_step)
for i in range(1, count):
x = math.floor(math.floor(i * big_tick_step) * pix_per_frame \
- pos * pix_per_frame) + 0.5
cr.move_to(x, SCALE_HEIGHT)
cr.line_to(x, BIG_TICK_Y)
cr.stroke()
# Draw tc
cr.select_font_face ("sans-serif",
cairo.FONT_SLANT_NORMAL,
cairo.FONT_WEIGHT_NORMAL)
cr.set_font_size(11)
start = int(view_start_frame / tc_draw_step)
# Get draw range in steps from 0
if start == pos:
start += 1 # don't draw line on first pixel of scale display
# +1 to ensure coverage
end = int(view_end_frame / tc_draw_step) + 1
for i in range(start, end):
x = math.floor(i * tc_draw_step * pix_per_frame \
- pos * pix_per_frame) + 0.5
cr.move_to(x, TC_Y)
text = utils.get_tc_string(i * tc_draw_step)
cr.show_text(text);
# Draw marks
self.draw_mark_in(cr, h)
self.draw_mark_out(cr, h)
# Draw markers
for i in range(0, len(seq.markers)):
marker_name, marker_frame = seq.markers[i]
x = math.floor(_get_frame_x(marker_frame))
cr.set_source_pixbuf(MARKER_ICON, x - 4, 15)
cr.paint()
# Select draw colors and frame based on mode
if EDIT_MODE() != editorstate.SLIDE_TRIM or PLAYER().looping():
current_frame = PLAYER().tracktor_producer.frame()
else:
current_frame = fake_current_frame
if timeline_visible():
cr.set_source_rgb(0, 0, 0)
line_color = (0, 0, 0)
else:
current_frame = editorstate.tline_shadow_frame
line_color = (0.8, 0.8, 0.8)
disp_frame = current_frame - pos
frame_x = math.floor(disp_frame * pix_per_frame) + 0.5
cr.set_source_rgb(*line_color)
cr.move_to(frame_x, 0)
cr.line_to(frame_x, h)
cr.stroke()
# Draw pos triangle
cr.set_source_pixbuf(TC_POINTER_HEAD, frame_x - 7.5, 0)
cr.paint()
def draw_mark_in(self, cr, h):
"""
Draws mark in graphic if set.
"""
mark_frame = current_sequence().tractor.mark_in
if mark_frame < 0:
return
x = _get_frame_x(mark_frame)
cr.set_source_rgb(*MARK_COLOR)
cr.move_to (x, MARK_PAD)
cr.line_to (x, h - MARK_PAD)
cr.line_to (x - 2 * MARK_LINE_WIDTH, h - MARK_PAD)
cr.line_to (x - 2 * MARK_LINE_WIDTH,
h - MARK_LINE_WIDTH - MARK_PAD)
cr.line_to (x - MARK_LINE_WIDTH, h - MARK_LINE_WIDTH - MARK_PAD )
cr.line_to (x - MARK_LINE_WIDTH, MARK_LINE_WIDTH + MARK_PAD)
cr.line_to (x - 2 * MARK_LINE_WIDTH, MARK_LINE_WIDTH + MARK_PAD )
cr.line_to (x - 2 * MARK_LINE_WIDTH, MARK_PAD)
cr.close_path();
cr.fill()
def draw_mark_out(self, cr, h):
"""
Draws mark out graphic if set.
"""
mark_frame = current_sequence().tractor.mark_out
if mark_frame < 0:
return
x = _get_frame_x(mark_frame + 1)
cr.set_source_rgb(*MARK_COLOR)
cr.move_to (x, MARK_PAD)
cr.line_to (x, h - MARK_PAD)
cr.line_to (x + 2 * MARK_LINE_WIDTH, h - MARK_PAD)
cr.line_to (x + 2 * MARK_LINE_WIDTH,
h - MARK_LINE_WIDTH - MARK_PAD)
cr.line_to (x + MARK_LINE_WIDTH, h - MARK_LINE_WIDTH - MARK_PAD )
cr.line_to (x + MARK_LINE_WIDTH, MARK_LINE_WIDTH + MARK_PAD)
cr.line_to (x + 2 * MARK_LINE_WIDTH, MARK_LINE_WIDTH + MARK_PAD )
cr.line_to (x + 2 * MARK_LINE_WIDTH, MARK_PAD)
cr.close_path();
cr.fill()
class TimeLineScroller(gtk.HScrollbar):
"""
Scrollbar for timeline.
"""
def __init__(self, scroll_listener):
gtk.HScrollbar.__init__(self)
adjustment = gtk.Adjustment(0.0, 0.0, 100.0, 1.0, 10.0, 30.0)
adjustment.connect("value-changed", scroll_listener)
self.set_adjustment(adjustment)
class ValueTester:
"""
Calls listener if test value in hit range.
"""
def __init__(self, start, end, listener):
self.start = start
self.end = end
self.listener = listener
self.data = utils.EmptyClass()
def call_listener_if_hit(self, value):
if value >= self.start and value <= self.end:
self.listener(self.data)
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2015 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
import pygtk
pygtk.require('2.0');
import gtk
import mlt
import locale
import os
import pango
import subprocess
import sys
import threading
import appconsts
import dialogs
import dialogutils
import editorstate
import editorpersistance
import guiutils
import guicomponents
import mltenv
import mltprofiles
import mlttransitions
import mltfilters
import patternproducer
import persistance
import projectdata
import propertyparse
import respaths
import renderconsumer
import translations
linker_window = None
target_project = None
media_assets = []
def display_linker():
print "Launching Media Re-linker"
FNULL = open(os.devnull, 'w')
subprocess.Popen([sys.executable, respaths.LAUNCH_DIR + "flowblademedialinker"], stdin=FNULL, stdout=FNULL, stderr=FNULL)
# -------------------------------------------------------- render thread
class ProjectLoadThread(threading.Thread):
def __init__(self, filename):
threading.Thread.__init__(self)
self.filename = filename
def run(self):
gtk.gdk.threads_enter()
linker_window.project_label.set_text("Loading...")
gtk.gdk.threads_leave()
persistance.show_messages = False
project = persistance.load_project(self.filename, False, True)
global target_project
target_project = project
target_project.c_seq = project.sequences[target_project.c_seq_index]
_update_media_assets()
gtk.gdk.threads_enter()
linker_window.relink_list.fill_data_model()
linker_window.project_label.set_text(self.filename)
linker_window.set_active_state()
linker_window.update_files_info()
gtk.gdk.threads_leave()
class MediaLinkerWindow(gtk.Window):
def __init__(self):
gtk.Window.__init__(self)
self.connect("delete-event", lambda w, e:_shutdown())
app_icon = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "flowblademedialinker.png")
self.set_icon_list(app_icon)
load_button = gtk.Button(_("Load Project For Relinking"))
load_button.connect("clicked",
lambda w: self.load_button_clicked())
project_row = gtk.HBox(False, 2)
project_row.pack_start(load_button, False, False, 0)
project_row.pack_start(gtk.Label(), True, True, 0)
self.missing_label = guiutils.bold_label("<b>" + _("Original Media Missing:") + "</b> ")
self.found_label = guiutils.bold_label("<b>" + _("Original Media Found:") + "</b> ")
self.missing_count = gtk.Label()
self.found_count = gtk.Label()
self.proj = guiutils.bold_label("<b>" + _("Project:") + "</b> ")
self.project_label = gtk.Label(_("<not loaded>"))
missing_info = guiutils.get_left_justified_box([self.missing_label, guiutils.pad_label(2, 2), self.missing_count])
missing_info.set_size_request(250, 2)
found_info = guiutils.get_left_justified_box([self.found_label, guiutils.pad_label(2, 2), self.found_count])
status_row = gtk.HBox(False, 2)
status_row.pack_start(missing_info, False, False, 0)
status_row.pack_start(found_info, False, False, 0)
status_row.pack_start(gtk.Label(), True, True, 0)
status_row.pack_start(guiutils.pad_label(30, 12), False, False, 0)
status_row.pack_start(self.proj, False, False, 0)
status_row.pack_start(guiutils.pad_label(4, 12), False, False, 0)
status_row.pack_start(self.project_label, False, False, 0)
self.relink_list = MediaRelinkListView()
self.find_button = gtk.Button(_("Set File Relink Path"))
self.find_button.connect("clicked", lambda w: _set_button_pressed())
self.delete_button = gtk.Button(_("Delete File Relink Path"))
self.delete_button.connect("clicked", lambda w: _delete_button_pressed())
self.display_combo = gtk.combo_box_new_text()
self.display_combo.append_text(_("Display Missing Media Files"))
self.display_combo.append_text(_("Display Found Media Files"))
self.display_combo.set_active(0)
self.display_combo.connect("changed", self.display_list_changed)
buttons_row = gtk.HBox(False, 2)
buttons_row.pack_start(self.display_combo, False, False, 0)
buttons_row.pack_start(gtk.Label(), True, True, 0)
buttons_row.pack_start(self.delete_button, False, False, 0)
buttons_row.pack_start(guiutils.pad_label(4, 4), False, False, 0)
buttons_row.pack_start(self.find_button, False, False, 0)
self.save_button = gtk.Button(_("Save Relinked Project As..."))
self.save_button.connect("clicked", lambda w:_save_project_pressed())
cancel_button = gtk.Button(_("Close"))
cancel_button.connect("clicked", lambda w:_shutdown())
dialog_buttons_box = gtk.HBox(True, 2)
dialog_buttons_box.pack_start(cancel_button, True, True, 0)
dialog_buttons_box.pack_start(self.save_button, False, False, 0)
dialog_buttons_row = gtk.HBox(False, 2)
dialog_buttons_row.pack_start(gtk.Label(), True, True, 0)
dialog_buttons_row.pack_start(dialog_buttons_box, False, False, 0)
pane = gtk.VBox(False, 2)
pane.pack_start(project_row, False, False, 0)
pane.pack_start(guiutils.pad_label(24, 24), False, False, 0)
pane.pack_start(status_row, False, False, 0)
pane.pack_start(guiutils.pad_label(24, 2), False, False, 0)
pane.pack_start(self.relink_list, False, False, 0)
pane.pack_start(buttons_row, False, False, 0)
pane.pack_start(guiutils.pad_label(24, 24), False, False, 0)
pane.pack_start(dialog_buttons_row, False, False, 0)
align = gtk.Alignment()
align.set_padding(12, 12, 12, 12)
align.add(pane)
# Set pane and show window
self.add(align)
self.set_title(_("Media Relinker"))
self.set_position(gtk.WIN_POS_CENTER)
self.show_all()
self.set_resizable(False)
self.set_active_state()
def load_button_clicked(self):
dialogs.load_project_dialog(self.load_project_dialog_callback)
def load_project_dialog_callback(self, dialog, response_id):
if response_id == gtk.RESPONSE_ACCEPT:
filenames = dialog.get_filenames()
dialog.destroy()
global load_thread
load_thread = ProjectLoadThread(filenames[0])
load_thread.start()
else:
dialog.destroy()
def display_list_changed(self, display_combo):
self.relink_list.fill_data_model()
if display_combo.get_active() == 0:
self.relink_list.text_col_1.set_title(self.relink_list.missing_text)
else:
self.relink_list.text_col_1.set_title(self.relink_list.found_text)
def set_active_state(self):
active = (target_project != None)
self.save_button.set_sensitive(active)
self.relink_list.set_sensitive(active)
self.find_button.set_sensitive(active)
self.delete_button.set_sensitive(active)
self.display_combo.set_sensitive(active)
self.missing_label.set_sensitive(active)
self.found_label.set_sensitive(active)
self.missing_count.set_sensitive(active)
self.found_count.set_sensitive(active)
self.project_label.set_sensitive(active)
self.proj.set_sensitive(active)
def update_files_info(self):
found = 0
missing = 0
for asset in media_assets:
if asset.orig_file_exists:
found = found + 1
else:
missing = missing + 1
self.missing_count.set_text(str(missing))
self.found_count.set_text(str(found))
def get_selected_media_asset(self):
selection = self.relink_list.treeview.get_selection()
(model, rows) = selection.get_selected_rows()
row = max(rows[0])
if len(self.relink_list.assets) == 0:
return None
return self.relink_list.assets[row]
class MediaRelinkListView(gtk.VBox):
def __init__(self):
gtk.VBox.__init__(self)
self.assets = [] # Used to store list displayd data items
# Datamodel: text, text
self.storemodel = gtk.ListStore(str, str)
# Scroll container
self.scroll = gtk.ScrolledWindow()
self.scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.scroll.set_shadow_type(gtk.SHADOW_ETCHED_IN)
# View
self.treeview = gtk.TreeView(self.storemodel)
self.treeview.set_property("rules_hint", True)
self.treeview.set_headers_visible(True)
self.treeview.connect("button-press-event", self.row_pressed)
tree_sel = self.treeview.get_selection()
# Column views
self.missing_text = _("Missing Media File Path")
self.found_text = _("Found Media File Path")
self.text_col_1 = gtk.TreeViewColumn("text1")
self.text_col_1.set_title(self.missing_text)
self.text_col_2 = gtk.TreeViewColumn("text2")
self.text_col_2.set_title(_("Media File Re-link Path"))
# Cell renderers
self.text_rend_1 = gtk.CellRendererText()
self.text_rend_1.set_property("ellipsize", pango.ELLIPSIZE_START)
self.text_rend_2 = gtk.CellRendererText()
self.text_rend_2.set_property("ellipsize", pango.ELLIPSIZE_START)
self.text_rend_2.set_property("yalign", 0.0)
# Build column views
self.text_col_1.set_expand(True)
self.text_col_1.pack_start(self.text_rend_1)
self.text_col_1.add_attribute(self.text_rend_1, "text", 0)
self.text_col_2.set_expand(True)
self.text_col_2.pack_start(self.text_rend_2)
self.text_col_2.add_attribute(self.text_rend_2, "text", 1)
# Add column views to view
self.treeview.append_column(self.text_col_1)
self.treeview.append_column(self.text_col_2)
# Build widget graph and display
self.scroll.add(self.treeview)
self.pack_start(self.scroll)
self.scroll.show_all()
self.set_size_request(1100, 400)
def fill_data_model(self):
self.assets = []
self.storemodel.clear()
display_missing = linker_window.display_combo.get_active() == 0
for media_asset in media_assets:
if media_asset.orig_file_exists != display_missing:
if media_asset.relink_path == None:
relink = ""
else:
relink = media_asset.relink_path
row_data = [media_asset.orig_path, relink]
self.storemodel.append(row_data)
self.assets.append(media_asset)
if len(self.assets) > 0:
selection = self.treeview.get_selection()
selection.unselect_all()
selection.select_path(0)
self.scroll.queue_draw()
def get_selected_rows_list(self):
model, rows = self.treeview.get_selection().get_selected_rows()
return rows
def row_pressed(self, treeview, event):
# Only handle right mouse on row, not empty or left mouse
path_pos_tuple = treeview.get_path_at_pos(int(event.x), int(event.y))
if path_pos_tuple == None:
return False
if not (event.button == 3):
return False
# Show pop-up
path, column, x, y = path_pos_tuple
selection = treeview.get_selection()
selection.unselect_all()
selection.select_path(path)
row = int(max(path))
guicomponents.display_media_linker_popup_menu(row, treeview, _media_asset_menu_item_selected, event)
return True
# ----------------------------------------------------------- logic
class MediaAsset:
def __init__(self, orig_path):
self.orig_path = orig_path
self.orig_file_exists = os.path.isfile(orig_path)
self.relink_path = None
def _update_media_assets():
# Collect all media assets used by project
new_assets = []
asset_paths = {}
# Media file media assets
for media_file_id, media_file in target_project.media_files.iteritems():
if isinstance(media_file, patternproducer.AbstractBinClip):
continue
new_assets.append(MediaAsset(media_file.path))
asset_paths[media_file.path] = media_file.path
for seq in target_project.sequences:
# Clip media assets
for track in seq.tracks:
for i in range(0, len(track.clips)):
clip = track.clips[i]
# Only producer clips are affected
if (clip.is_blanck_clip == False and (clip.media_type != appconsts.PATTERN_PRODUCER)):
if not(clip.path in asset_paths):
new_assets.append(MediaAsset(clip.path))
asset_paths[clip.path] = clip.path
# Wipe lumas
for compositor in seq.compositors:
res_path = None
if compositor.type_id == "##wipe": # Wipe may have user luma and needs to be looked up relatively
res_path = propertyparse.get_property_value(compositor.transition.properties, "resource")
if compositor.type_id == "##region": # Wipe may have user luma and needs to be looked up relatively
res_path = propertyparse.get_property_value(compositor.transition.properties, "composite.luma")
if res_path != None:
if not(res_path in asset_paths):
new_assets.append(MediaAsset(res_path))
asset_paths[res_path] = res_path
global media_assets
media_assets = new_assets
def _media_asset_menu_item_selected(widget, data):
msg, row = data
media_asset = linker_window.relink_list.assets[row]
if msg == "set relink":
_set_relink_path(media_asset)
if msg == "delete relink":
_delete_relink_path(media_asset)
if msg == "show path":
_show_paths(media_asset)
def _set_button_pressed():
media_asset = linker_window.get_selected_media_asset()
if media_asset == None:
return
_set_relink_path(media_asset)
def _set_relink_path(media_asset):
file_name = os.path.basename(media_asset.orig_path)
dialogs.media_file_dialog(_("Select Media File To Relink To") + " " + file_name, _select_relink_path_dialog_callback, False, media_asset)
def _select_relink_path_dialog_callback(file_select, response_id, media_asset):
filenames = file_select.get_filenames()
file_select.destroy()
if response_id != gtk.RESPONSE_OK:
return
if len(filenames) == 0:
return
media_asset.relink_path = filenames[0]
linker_window.relink_list.fill_data_model()
def _delete_button_pressed():
media_asset = linker_window.get_selected_media_asset()
if media_asset == None:
return
_delete_relink_path(media_asset)
def _delete_relink_path(media_asset):
media_asset.relink_path = None
linker_window.relink_list.fill_data_model()
def _show_paths(media_asset):
orig_path_label = gtk.Label(_("<b>Original path:</b> "))
orig_path_label.set_use_markup(True)
orig_path = guiutils.get_left_justified_box([orig_path_label, gtk.Label(media_asset.orig_path)])
relink_path_label = gtk.Label(_("<b>Relink path:</b> "))
relink_path_label.set_use_markup(True)
relink_path = guiutils.get_left_justified_box([relink_path_label, gtk.Label(media_asset.relink_path)])
panel = gtk.VBox()
panel.pack_start(orig_path, False, False, 0)
panel.pack_start(guiutils.pad_label(12, 12), False, False, 0)
panel.pack_start(relink_path, False, False, 0)
dialogutils.panel_ok_dialog("Media Asset Paths", panel)
def _save_project_pressed():
if target_project.last_save_path != None:
open_dir = os.path.dirname(target_project.last_save_path)
else:
open_dir = None
no_ext_name = target_project.name.replace('.flb','')
dialogs.save_project_as_dialog(_save_as_dialog_callback,
no_ext_name + "_RELINKED.flb",
open_dir)
def _save_as_dialog_callback(dialog, response_id):
if response_id == gtk.RESPONSE_ACCEPT:
filenames = dialog.get_filenames()
dialog.destroy()
target_project.last_save_path = filenames[0]
target_project.name = os.path.basename(filenames[0])
_relink_project_media_paths()
persistance.save_project(target_project, target_project.last_save_path)
dialogutils.info_message(_("Relinked version of the Project saved!"),
_("To test the project, close this tool and open the relinked version in Flowblade."),
linker_window)
else:
dialog.destroy()
def _relink_project_media_paths():
# Collect relink paths
relinked_paths = {}
for media_asset in media_assets:
if media_asset.relink_path != None:
relinked_paths[media_asset.orig_path] = media_asset.relink_path
# Relink media file media assets
for media_file_id, media_file in target_project.media_files.iteritems():
if isinstance(media_file, patternproducer.AbstractBinClip):
continue
if media_file.path in relinked_paths:
media_file.path = relinked_paths[media_file.path]
for seq in target_project.sequences:
# Relink clip media assets
for track in seq.tracks:
for i in range(0, len(track.clips)):
clip = track.clips[i]
if (clip.is_blanck_clip == False and (clip.media_type != appconsts.PATTERN_PRODUCER)):
if clip.path in relinked_paths:
clip.path = relinked_paths[clip.path]
# Relink wipe lumas
for compositor in seq.compositors:
if compositor.type_id == "##wipe":
res_path = propertyparse.get_property_value(compositor.transition.properties, "resource")
if res_path in relinked_paths:
propertyparse.set_property_value(compositor.transition.properties, "resource", relinked_paths[res_path])
if compositor.type_id == "##region":
res_path = propertyparse.get_property_value(compositor.transition.properties, "composite.luma")
if res_path in relinked_paths:
propertyparse.set_property_value(compositor.transition.properties, "composite.luma", relinked_paths[res_path])
# ----------------------------------------------------------- main
def main(root_path, force_launch=False):
editorstate.gtk_version = gtk.gtk_version
try:
editorstate.mlt_version = mlt.LIBMLT_VERSION
except:
editorstate.mlt_version = "0.0.99" # magic string for "not found"
# Set paths.
respaths.set_paths(root_path)
# Init translations module with translations data
translations.init_languages()
translations.load_filters_translations()
mlttransitions.init_module()
# Load editor prefs and list of recent projects
editorpersistance.load()
# Init gtk threads
gtk.gdk.threads_init()
gtk.gdk.threads_enter()
repo = mlt.Factory().init()
# Set numeric locale to use "." as radix, MLT initilizes this to OS locale and this causes bugs
locale.setlocale(locale.LC_NUMERIC, 'C')
# Check for codecs and formats on the system
mltenv.check_available_features(repo)
renderconsumer.load_render_profiles()
# Load filter and compositor descriptions from xml files.
mltfilters.load_filters_xml(mltenv.services)
mlttransitions.load_compositors_xml(mltenv.transitions)
# Create list of available mlt profiles
mltprofiles.load_profile_list()
appconsts.SAVEFILE_VERSION = projectdata.SAVEFILE_VERSION
global linker_window
linker_window = MediaLinkerWindow()
gtk.main()
gtk.gdk.threads_leave()
def _shutdown():
gtk.main_quit()
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module contents:
class PositionBar - Displays position on a clip or a sequence
"""
import pygtk
pygtk.require('2.0');
import gtk
import cairo
from cairoarea import CairoDrawableArea
import editorpersistance
import editorstate
import trimmodes
# Draw params
BAR_WIDTH = 200 # NOTE: DOES NOT HAVE ANY EFFECT IF OTHER WIDTHS MAKE MONITOR AREA MIN WIDTH BIGGER, AS THIS EXPANDS TO FILL
BAR_HEIGHT = 20 # component height
LINE_WIDTH = 3
LINE_HEIGHT = 6
LINE_COLOR = (0.3, 0.3, 0.3)
LINE_COUNT = 11 # Number of range lines
BG_COLOR = (1, 1, 1)
DISABLED_BG_COLOR = (0.7, 0.7, 0.7)
SELECTED_RANGE_COLOR = (0.85, 0.85, 0.85)
DARK_LINE_COLOR = (0.9, 0.9, 0.9)
DARK_BG_COLOR = (0.3, 0.3, 0.3)
DARK_DISABLED_BG_COLOR = (0.1, 0.1, 0.1)
DARK_SELECTED_RANGE_COLOR = (0.5, 0.5, 0.5)
SPEED_TEST_COLOR = (0.5, 0.5, 0.5)
POINTER_COLOR = (1, 0.3, 0.3)
END_PAD = 6 # empty area at both ends in pixels
MARK_CURVE = 5
MARK_LINE_WIDTH = 4
MARK_PAD = 4
MARK_COLOR = (0.3, 0.3, 0.3)
DARK_MARK_COLOR = (0.1, 0.1, 0.1)
class PositionBar:
"""
GUI component used to set/display position in clip/timeline
"""
def __init__(self):
self.widget = CairoDrawableArea(BAR_WIDTH,
BAR_HEIGHT,
self._draw)
self.widget.press_func = self._press_event
self.widget.motion_notify_func = self._motion_notify_event
self.widget.release_func = self._release_event
self._pos = END_PAD # in display pixels
self.mark_in_norm = -1.0 # program length normalized
self.mark_out_norm = -1.0
self.disabled = False
self.mouse_release_listener = None # when used in tools (Tiler ate.) this used to update bg image
if editorpersistance.prefs.dark_theme == True:
global LINE_COLOR, BG_COLOR, DISABLED_BG_COLOR, SELECTED_RANGE_COLOR, MARK_COLOR
LINE_COLOR = DARK_LINE_COLOR
BG_COLOR = DARK_BG_COLOR
DISABLED_BG_COLOR = DARK_DISABLED_BG_COLOR
SELECTED_RANGE_COLOR = DARK_SELECTED_RANGE_COLOR
MARK_COLOR = DARK_MARK_COLOR
def set_listener(self, listener):
self.position_listener = listener
def set_normalized_pos(self, norm_pos):
"""
Sets position in range 0 - 1
"""
self._pos = self._get_panel_pos(norm_pos)
self.widget.queue_draw()
def update_display_from_producer(self, producer):
self.producer = producer
length = producer.get_length() # Get from MLT
try:
self.mark_in_norm = float(producer.mark_in) / length
self.mark_out_norm = float(producer.mark_out) / length
frame_pos = producer.frame()
norm_pos = float(frame_pos) / length
self._pos = self._get_panel_pos(norm_pos)
except ZeroDivisionError:
self.mark_in_norm = 0
self.mark_out_norm = 0
self._pos = self._get_panel_pos(0)
self.widget.queue_draw()
def _get_panel_pos(self, norm_pos):
return END_PAD + int(norm_pos *
(self.widget.allocation.width - 2 * END_PAD))
def _draw(self, event, cr, allocation):
"""
Callback for repaint from CairoDrawableArea.
We get cairo contect and allocation.
"""
x, y, w, h = allocation
# Draw bb
draw_color = BG_COLOR
if self.disabled:
draw_color = DISABLED_BG_COLOR
cr.set_source_rgb(*draw_color)
cr.rectangle(0,0,w,h)
cr.fill()
# Draw selected area if marks set
if self.mark_in_norm >= 0 and self.mark_out_norm >= 0:
cr.set_source_rgb(*SELECTED_RANGE_COLOR)
m_in = self._get_panel_pos(self.mark_in_norm)
m_out = self._get_panel_pos(self.mark_out_norm)
cr.rectangle(m_in, 0, m_out - m_in, h)
cr.fill()
# Get area between end pads
active_width = w - 2 * END_PAD
# Draw lines
cr.set_line_width(1.0)
x_step = float(active_width) / (LINE_COUNT)
for i in range(LINE_COUNT + 1):
cr.move_to(int((i) * x_step) + END_PAD + 0.5, -0.5)
cr.line_to(int((i) * x_step) + END_PAD + 0.5, LINE_HEIGHT + 0.5)
for i in range(LINE_COUNT + 1):
cr.move_to(int((i) * x_step) + END_PAD + 0.5, BAR_HEIGHT)
cr.line_to(int((i) * x_step) + END_PAD + 0.5,
BAR_HEIGHT - LINE_HEIGHT + 0.5)
cr.set_source_rgb(*LINE_COLOR)
cr.stroke()
# Draw mark in and mark out
self.draw_mark_in(cr, h)
self.draw_mark_out(cr, h)
# Draw position pointer
if self.disabled:
return
cr.set_line_width(2.0)
cr.set_source_rgb(*POINTER_COLOR)
cr.move_to(self._pos + 0.5, 0)
cr.line_to(self._pos + 0.5, BAR_HEIGHT)
cr.stroke()
speed = editorstate.PLAYER().producer.get_speed()
if speed != 1.0 and speed != 0.0:
cr.set_source_rgb(*SPEED_TEST_COLOR)
cr.select_font_face ("sans-serif",
cairo.FONT_SLANT_NORMAL,
cairo.FONT_WEIGHT_BOLD)
cr.set_font_size(11)
disp_str = str(speed) + "x"
tx, ty, twidth, theight, dx, dy = cr.text_extents(disp_str)
cr.move_to( w/2 - twidth/2, 13)
cr.show_text(disp_str)
def draw_mark_in(self, cr, h):
"""
Draws mark in graphic if set.
"""
if self.mark_in_norm < 0:
return
x = self._get_panel_pos(self.mark_in_norm)
cr.move_to (x, MARK_PAD)
cr.line_to (x, h - MARK_PAD)
cr.line_to (x - 2 * MARK_LINE_WIDTH, h - MARK_PAD)
cr.line_to (x - 2 * MARK_LINE_WIDTH,
h - MARK_LINE_WIDTH - MARK_PAD)
cr.line_to (x - MARK_LINE_WIDTH, h - MARK_LINE_WIDTH - MARK_PAD )
cr.line_to (x - MARK_LINE_WIDTH, MARK_LINE_WIDTH + MARK_PAD)
cr.line_to (x - 2 * MARK_LINE_WIDTH, MARK_LINE_WIDTH + MARK_PAD )
cr.line_to (x - 2 * MARK_LINE_WIDTH, MARK_PAD)
cr.close_path();
cr.set_source_rgb(*MARK_COLOR)
cr.fill()
def draw_mark_out(self, cr, h):
"""
Draws mark out graphic if set.
"""
if self.mark_out_norm < 0:
return
x = self._get_panel_pos(self.mark_out_norm)
cr.move_to (x, MARK_PAD)
cr.line_to (x, h - MARK_PAD)
cr.line_to (x + 2 * MARK_LINE_WIDTH, h - MARK_PAD)
cr.line_to (x + 2 * MARK_LINE_WIDTH,
h - MARK_LINE_WIDTH - MARK_PAD)
cr.line_to (x + MARK_LINE_WIDTH, h - MARK_LINE_WIDTH - MARK_PAD )
cr.line_to (x + MARK_LINE_WIDTH, MARK_LINE_WIDTH + MARK_PAD)
cr.line_to (x + 2 * MARK_LINE_WIDTH, MARK_LINE_WIDTH + MARK_PAD )
cr.line_to (x + 2 * MARK_LINE_WIDTH, MARK_PAD)
cr.close_path();
cr.set_source_rgb(*MARK_COLOR)
cr.fill()
def _press_event(self, event):
"""
Mouse button callback
"""
if self.disabled:
return
if editorstate.timeline_visible():
trimmodes.set_no_edit_trim_mode()
if((event.button == 1)
or(event.button == 3)):
# Set pos to in active range to get normalized pos
self._pos = self._legalize_x(event.x)
# Listener calls self.set_normalized_pos()
# _pos gets actually set twice
# Listener also updates other frame displayers
self.position_listener(self.normalized_pos(), self.producer.get_length())
def _motion_notify_event(self, x, y, state):
"""
Mouse move callback
"""
if self.disabled:
return
if((state & gtk.gdk.BUTTON1_MASK)
or (state & gtk.gdk.BUTTON3_MASK)):
self._pos = self._legalize_x(x)
# Listener calls self.set_normalized_pos()
self.position_listener(self.normalized_pos(), self.producer.get_length())
def _release_event(self, event):
"""
Mouse release callback.
"""
if self.disabled:
return
self._pos = self._legalize_x(event.x)
# Listener calls self.set_normalized_pos()
self.position_listener(self.normalized_pos(), self.producer.get_length())
if self.mouse_release_listener != None:
self.mouse_release_listener(self.normalized_pos(), self.producer.get_length())
def _legalize_x(self, x):
"""
Get x in pixel range corresponding normalized position 0.0 - 1.0.
This is needed because of end pads.
"""
w = self.widget.allocation.width
if x < END_PAD:
return END_PAD
elif x > w - END_PAD:
return w - END_PAD
else:
return x
def normalized_pos(self):
return float(self._pos - END_PAD) / \
(self.widget.allocation.width - END_PAD * 2)
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module contains an object that is used to do playback from mlt.Producers to
a Xwindow of a GTK+ widget and os audiosystem using a SDL consumer.
"""
import pygtk
pygtk.require('2.0');
import gtk
import mlt
import os
import time
import gui
import editorpersistance
from editorstate import timeline_visible
import editorstate
import utils
import updater
TICKER_DELAY = 0.25
RENDER_TICKER_DELAY = 0.05
class Player:
def __init__(self, profile):
self.init_for_profile(profile)
self.ticker = utils.Ticker(self._ticker_event, TICKER_DELAY)
def init_for_profile(self, profile):
# Get profile and create ticker for playback GUI updates
self.profile = profile
print "Player initialized with profile: ", self.profile.description()
# Trim loop preview
self.loop_start = -1
self.loop_end = -1
self.is_looping = False
# Rendering
self.is_rendering = False
self.render_stop_frame = -1
self.render_start_frame = -1
self.render_callbacks = None
self.wait_for_producer_end_stop = True
self.render_gui_update_count = 0
# JACK audio
self.jack_output_filter = None
def create_sdl_consumer(self):
"""
Creates consumer with sdl output to a gtk+ widget.
"""
# Create consumer and set params
self.consumer = mlt.Consumer(self.profile, "sdl")
self.consumer.set("real_time", 1)
self.consumer.set("rescale", "bicubic") # MLT options "nearest", "bilinear", "bicubic", "hyper"
self.consumer.set("resize", 1)
self.consumer.set("progressive", 1)
# Hold ref to switch back from rendering
self.sdl_consumer = self.consumer
def set_sdl_xwindow(self, widget):
"""
Connects SDL output to display widget's xwindow
"""
os.putenv('SDL_WINDOWID', str(widget.window.xid))
gtk.gdk.flush()
def set_tracktor_producer(self, tractor):
"""
Sets a MLT producer from multitrack timeline to be displayed.
"""
self.tracktor_producer = tractor
self.producer = tractor
def display_tractor_producer(self):
self.producer = self.tracktor_producer
self.connect_and_start()
def refresh(self): # Window events need this to get picture back
self.consumer.stop()
self.consumer.start()
def is_stopped(self):
return (self.producer.get_speed() == 0)
def stop_consumer(self):
if not self.consumer.is_stopped():
self.consumer.stop()
def connect_and_start(self):
"""
Connects current procer and consumer and
"""
self.consumer.purge()
self.producer.set_speed(0)
self.consumer.connect(self.producer)
self.consumer.start()
def start_playback(self):
"""
Starts playback from current producer
"""
self.producer.set_speed(1)
self.ticker.stop_ticker()
self.ticker.start_ticker()
def start_variable_speed_playback(self, speed):
"""
Starts playback from current producer
"""
#print speed
self.producer.set_speed(speed)
self.ticker.stop_ticker()
self.ticker.start_ticker()
def stop_playback(self):
"""
Stops playback from current producer
"""
self.ticker.stop_ticker()
self.producer.set_speed(0)
updater.update_frame_displayers(self.producer.frame())
updater.maybe_autocenter()
def start_loop_playback(self, cut_frame, loop_half_length, track_length):
self.loop_start = cut_frame - loop_half_length
self.loop_end = cut_frame + loop_half_length
if self.loop_start < 0:
self.loop_start = 0
if self.loop_end >= track_length:
self.loop_end = track_length - 1
self.is_looping = True
self.seek_frame(self.loop_start, False)
self.producer.set_speed(1)
self.ticker.stop_ticker()
self.ticker.start_ticker()
def stop_loop_playback(self, looping_stopped_callback):
"""
Stops playback from current producer
"""
self.loop_start = -1
self.loop_end = -1
self.is_looping = False
self.producer.set_speed(0)
self.ticker.stop_ticker()
looping_stopped_callback() # Re-creates hidden track that was cleared for looping playback
def looping(self):
return self.is_looping
def current_frame(self):
return self.producer.frame()
def seek_position_normalized(self, pos, length):
frame_number = pos * length
self.seek_frame(int(frame_number))
def seek_delta(self, delta):
# Get new frame
frame = self.producer.frame() + delta
# Seek frame
self.seek_frame(frame)
def seek_frame(self, frame, update_gui=True):
# Force range
length = self.get_active_length()
if frame < 0:
frame = 0
elif frame >= length:
frame = length - 1
self.producer.set_speed(0)
self.producer.seek(frame)
# GUI update path starts here.
# All user or program initiated seeks go through this method.
if update_gui:
updater.update_frame_displayers(frame)
def seek_and_get_rgb_frame(self, frame, update_gui=True):
# Force range
length = self.get_active_length()
if frame < 0:
frame = 0
elif frame >= length:
frame = length - 1
self.producer.set_speed(0)
self.producer.seek(frame)
# GUI update path starts here.
# All user or program initiated seeks go through this method.
if update_gui:
updater.update_frame_displayers(frame)
frame = self.producer.get_frame()
# And make sure we deinterlace if input is interlaced
frame.set("consumer_deinterlace", 1)
# Now we are ready to get the image and save it.
size = (self.profile.width(), self.profile.height())
rgb = frame.get_image(mlt.mlt_image_rgb24a, *size)
return rgb
def display_inside_sequence_length(self, new_seq_len):
if self.producer.frame() > new_seq_len:
self.seek_frame(new_seq_len)
def is_playing(self):
return (self.producer.get_speed() != 0)
def _ticker_event(self):
# Stop ticker if playback has stopped.
if (self.consumer.is_stopped() or self.producer.get_speed() == 0):
self.ticker.stop_ticker()
current_frame = self.producer.frame()
# Stop rendering if last frame reached.
if self.is_rendering == True and current_frame >= self.render_stop_frame:
self.stop_rendering()
return
# If we're currently rendering, set progress bar and exit event handler.
if self.is_rendering:
if (self.producer.get_length() - 1) < 1:
render_fraction = 1.0
else:
render_fraction = ((float(current_frame - self.render_start_frame)) /
(float(self.render_stop_frame - self.render_start_frame)))
self.render_gui_update_count = self.render_gui_update_count + 1
if self.render_gui_update_count % 8 == 0: # we need quick updates for stop accuracy, but slower gui updating
self.render_gui_update_count = 1
gtk.gdk.threads_enter()
self.render_callbacks.set_render_progress_gui(render_fraction)
gtk.gdk.threads_leave()
return
# If we're out of active range seek end.
if current_frame >= self.get_active_length():
gtk.gdk.threads_enter()
self.seek_frame(current_frame)
gtk.gdk.threads_leave()
return
# If trim looping and past loop end, start from loop start
if ((not(self.loop_start == -1)) and
((current_frame >= self.loop_end)
or (current_frame >= self.get_active_length()))):
self.seek_frame(self.loop_start, False) #NOTE: False==GUI not updated
self.producer.set_speed(1)
gtk.gdk.threads_enter()
updater.update_frame_displayers(current_frame)
gtk.gdk.threads_leave()
def get_active_length(self):
# Displayed range is different
# for timeline and clip displays
if timeline_visible():
return self.producer.get_length()
else:
return gui.pos_bar.producer.get_length()
def get_render_fraction(self):
if self.render_stop_frame == -1:
return float(self.producer.frame()) / float(self.producer.get_length() - 1)
else:
return float(self.producer.frame() - self.render_start_frame) / float(self.render_stop_frame - self.render_start_frame)
def set_render_callbacks(self, callbacks):
# Callbacks object interface:
#
# callbacks = utils.EmptyClass()
# callbacks.set_render_progress_gui(fraction)
# callbacks.save_render_start_time()
# callbacks.exit_render_gui()
# callbacks.maybe_open_rendered_file_in_bin()
self.render_callbacks = callbacks
def start_rendering(self, render_consumer, start_frame=0, stop_frame=-1):
if stop_frame == -1:
stop_frame = self.producer.get_length() - 1
if stop_frame >= self.producer.get_length() - 1:
self.wait_for_producer_end_stop = True
else:
self.wait_for_producer_end_stop = False
print "start_rendering(), start frame :" + str(start_frame) + ", stop_frame: " + str(stop_frame)
self.ticker.stop_ticker()
self.consumer.stop()
self.producer.set_speed(0)
self.producer.seek(start_frame)
time.sleep(0.5) # We need to be at correct frame before starting rendering or firts frame may get dropped
self.render_start_frame = start_frame
self.render_stop_frame = stop_frame
self.consumer = render_consumer
self.consumer.connect(self.producer)
self.consumer.start()
self.producer.set_speed(1)
self.is_rendering = True
self.render_callbacks.save_render_start_time()
self.ticker.start_ticker(RENDER_TICKER_DELAY)
def stop_rendering(self):
print "stop_rendering, producer frame: " + str(self.producer.frame())
# Stop render
# This method of stopping makes sure that whole producer is rendered and written to disk
if self.wait_for_producer_end_stop:
while self.producer.get_speed() > 0:
time.sleep(0.2)
while not self.consumer.is_stopped():
time.sleep(0.2)
# This method of stopping stops producer
# and waits for consumer to reach that frame.
else:
self.producer.set_speed(0)
last_frame = self.producer.frame()
# Make sure consumer renders all frames before exiting
while self.consumer.position() + 1 < last_frame:
time.sleep(0.2)
self.consumer.stop()
# Exit render state
self.is_rendering = False
self.ticker.stop_ticker()
self.producer.set_speed(0)
# Enter monitor playback state
self.consumer = self.sdl_consumer
gtk.gdk.threads_enter()
self.connect_and_start()
gtk.gdk.threads_leave()
self.seek_frame(0)
gtk.gdk.threads_enter()
self.render_callbacks.exit_render_gui()
self.render_callbacks.maybe_open_rendered_file_in_bin()
gtk.gdk.threads_leave()
def jack_output_on(self):
# We're assuming that we are not rendering and consumer is SDL consumer
self.producer.set_speed(0)
self.ticker.stop_ticker()
self.consumer.stop()
self.create_sdl_consumer()
self.jack_output_filter = mlt.Filter(self.profile, "jackrack")
if editorpersistance.prefs.jack_output_type == appconsts.JACK_OUT_AUDIO:
self.jack_output_filter.set("out_1", "system:playback_1")
self.jack_output_filter.set("out_2", "system:playback_2")
self.consumer.attach(self.jack_output_filter)
self.consumer.set("audio_off", "1")
self.consumer.set("frequency", str(editorpersistance.prefs.jack_frequency))
self.consumer.connect(self.producer)
self.consumer.start()
def jack_output_off(self):
# We're assuming that we are not rendering and consumer is SDL consumer
self.producer.set_speed(0)
self.ticker.stop_ticker()
self.consumer.detach(self.jack_output_filter)
self.consumer.set("audio_off", "0")
self.consumer.stop()
self.consumer.start()
self.jack_output_filter = None
def shutdown(self):
self.ticker.stop_ticker()
self.producer.set_speed(0)
self.consumer.stop()
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module handles editing positions and clip ends of compositors on timeline.
"""
import gui
import edit
import editorstate
from editorstate import current_sequence
import tlinewidgets
import updater
TRIM_HANDLE_WIDTH = 10
MOVE_EDIT = 0
TRIM_EDIT = 1
compositor = None
edit_data = None
sub_mode = None
prev_edit_mode = None
def set_compositor_mode(new_compositor):
global prev_edit_mode
prev_edit_mode = editorstate.EDIT_MODE()
editorstate.edit_mode = editorstate.COMPOSITOR_EDIT
set_compositor_selected(new_compositor)
def set_compositor_selected(new_compositor):
global compositor
if compositor != None:
compositor.selected = False
compositor = new_compositor
compositor.selected = True
def clear_compositor_selection():
global compositor
if compositor == None:
return
compositor.selected = False
compositor = None
def delete_current_selection():
global compositor
if compositor == None:
return
data = {"compositor":compositor}
action = edit.delete_compositor_action(data)
action.do_edit()
compositor.selected = False # this may return in undo?
compositor = None
def mouse_press(event, frame):
track = current_sequence().tracks[compositor.transition.b_track - 1]
global edit_data, sub_mode
compositor_y = tlinewidgets._get_track_y(track.id) - tlinewidgets.COMPOSITOR_HEIGHT_OFF
if abs(event.x - tlinewidgets._get_frame_x(compositor.clip_in)) < TRIM_HANDLE_WIDTH:
edit_data = {"clip_in":compositor.clip_in,
"clip_out":compositor.clip_out,
"trim_is_clip_in":True,
"compositor_y": compositor_y,
"compositor": compositor}
tlinewidgets.set_edit_mode(edit_data, tlinewidgets.draw_compositor_trim)
sub_mode = TRIM_EDIT
elif abs(event.x - tlinewidgets._get_frame_x(compositor.clip_out + 1)) < TRIM_HANDLE_WIDTH:
edit_data = {"clip_in":compositor.clip_in,
"clip_out":compositor.clip_out,
"trim_is_clip_in":False,
"compositor_y": compositor_y,
"compositor": compositor}
tlinewidgets.set_edit_mode(edit_data, tlinewidgets.draw_compositor_trim)
sub_mode = TRIM_EDIT
else:
edit_data = {"press_frame":frame,
"current_frame":frame,
"clip_in":compositor.clip_in,
"clip_length":(compositor.clip_out - compositor.clip_in + 1),
"compositor_y": compositor_y,
"compositor": compositor}
tlinewidgets.set_edit_mode(edit_data, tlinewidgets.draw_compositor_move_overlay)
sub_mode = MOVE_EDIT
updater.repaint_tline()
def mouse_move(x, y, frame, state):
global edit_data
if sub_mode == TRIM_EDIT:
_bounds_check_trim(frame, edit_data)
else:
edit_data["current_frame"] = frame
updater.repaint_tline()
def mouse_release(x, y, frame, state):
editorstate.edit_mode = prev_edit_mode
if editorstate.edit_mode == editorstate.INSERT_MOVE:
tlinewidgets.set_edit_mode(None, tlinewidgets.draw_insert_overlay)
elif editorstate.edit_mode == editorstate.INSERT_MOVE:
tlinewidgets.set_edit_mode(None, tlinewidgets.draw_overwrite_overlay)
elif editorstate.edit_mode == editorstate.MULTI_MOVE:
tlinewidgets.set_edit_mode(None, tlinewidgets.draw_multi_overlay)
else:
print "COMPOSITOR MODE EXIT PROBLEM at compositormodes.mouse_release"
gui.editor_window.set_cursor_to_mode()
if sub_mode == TRIM_EDIT:
_bounds_check_trim(frame, edit_data)
data = {"compositor":compositor,
"clip_in":edit_data["clip_in"],
"clip_out":edit_data["clip_out"]}
action = edit.move_compositor_action(data)
action.do_edit()
else:
press_frame = edit_data["press_frame"]
current_frame = frame
delta = current_frame - press_frame
data = {"compositor":compositor,
"clip_in":compositor.clip_in + delta,
"clip_out":compositor.clip_out + delta}
if data["clip_in"] < 0:
data["clip_in"] = 0
if data["clip_out"] < 0:
data["clip_out"] = 0
action = edit.move_compositor_action(data)
action.do_edit()
updater.repaint_tline()
def _bounds_check_trim(frame, edit_data):
if edit_data["trim_is_clip_in"] == True:
if frame > edit_data["clip_out"]:
frame = edit_data["clip_out"]
edit_data["clip_in"] = frame
else:
if frame < edit_data["clip_in"]:
frame = edit_data["clip_in"]
edit_data["clip_out"] = frame
if edit_data["clip_in"] < 0:
edit_data["clip_in"] = 0
if edit_data["clip_out"] < 0:
edit_data["clip_out"] = 0
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module provides wrapper objects for editing property values of objects in
the sequence.
Properties are (name, value, type) tuples that are wrapped in objects
extending AbstractProperty class for editing. These wrappers convert
edit inputs into mlt property values (that effect how sequence is displayed)
and python side values (that are persistant).
"""
import pygtk
pygtk.require('2.0');
import gtk
import appconsts
from editorstate import current_sequence
import mlttransitions
import mltfilters
import propertyparse
import utils
# keys meaning of values for this key
RANGE_IN = "range_in" # values define user input range
RANGE_OUT = "range_out" # values define range of output to mlt
STEP = "step" # gtk.Adjustment step_increment value is set using this
EXPRESSION_TYPE = "exptype" # type of string expression used as value
EDITOR = "editor" # editor used to edit property
DISPLAY_NAME = "displayname" # name of property that is displayed to user
MULTIPART_START_PROP = "multistartprop" # Value used to set multipart value at part start
MULTIPART_END_PROP = "multiendprop" # Value used to set multipart value at part end
# ranges values expression is replaced with
NORMALIZED_FLOAT = "NORMALIZED_FLOAT" # range 0.0 - 1.0
# PROP_EXPRESSION values, e.g. "exptype=keyframe_hcs" parsed output
DEFAULT = "default" # value (str(int), str(float) or str(str))
DEFAULT_TRANSITION = "default_transition" # value (str(int), str(float) or str(str))
SINGLE_KEYFRAME = "singlekeyframe" # 0=value
OPACITY_IN_GEOM_SINGLE_KF = "opacity_in_geom_kf_single" # 0=0/0:SCREEN_WIDTHxSCREEN_HEIGHT:opacity
OPACITY_IN_GEOM_KF = "opacity_in_geom_kf" # frame=0/0:SCREEN_WIDTHxSCREEN_HEIGHT:opacity (kf_str;kf_str;kf_str;...;kf_str)
GEOMETRY_OPACITY_KF ="geom_opac_kf" # frame=x/y:widthxheight:opacity
GEOM_IN_AFFINE_FILTER = "geom_in_affine_filt" # x/y:widthxheight:opacity
AFFINE_SCALE = "affine_scale" # special property to get the 1/ x that the filter wants
KEYFRAME_HCS = "keyframe_hcs" # frame=value(;frame=value) HCS = half comma separeted
KEYFRAME_HCS_TRANSITION = "keyframe_hcs_transition" # frame=value(;frame=value) HCS = half comma separeted, used to edit transitions
MULTIPART_KEYFRAME_HCS = "multipart_keyframe" # frame=value(;frame=value) series of mlt.Filter objects that get their properties set, HCS = half comma separeted
FREI_POSITION_HCS = "frei_pos_hcs" # frame=x:y
FREI_GEOM_HCS_TRANSITION = "frei_geom_hcs"; # time=x:y:x_scale:y_scale:rotation:mix
COLOR = "color" # #rrggbb
LUT_TABLE = "lut_table" # val;val;val;val;...;val
WIPE_RESOURCE = "wipe_resource" # /path/to/resource.pgm
NOT_PARSED = "not_parsed" # A write out value is not parsed from value
NOT_PARSED_TRANSITION = "not_parsed_transition" # A write out value is not parsed from value in transition object
DEFAULT_STEP = 1.0 # for sliders
def get_filter_editable_properties(clip, filter_object, filter_index,
track, clip_index, compositor_filter=False):
"""
Creates EditableProperty wrappers for all property tuples in a
mltfilters.FilterObject and returns them in array.
"""
editable_properties = []
# Editable properties for normal filters
for i in range(0, len(filter_object.properties)):
p_name, p_value, p_type = filter_object.properties[i]
args_str = filter_object.info.property_args[p_name]
params = (clip, filter_index, (p_name, p_value, p_type), i, args_str)
ep = _create_editable_property(p_type, args_str, params)
ep.is_compositor_filter = compositor_filter
ep.track = track
ep.clip_index = clip_index
editable_properties.append(ep)
# Editable property for multipart filters
if isinstance(filter_object, mltfilters.MultipartFilterObject):
args_str, start_property, end_property = filter_object.info.multipart_desc
property_index = len(editable_properties)
params = (clip, filter_index,
("no dispname given", filter_object.value, appconsts.PROP_EXPRESSION),
property_index, args_str)
ep = _create_editable_property(appconsts.PROP_EXPRESSION, args_str, params)
ep.is_compositor_filter = compositor_filter
ep.track = track
ep.clip_index = clip_index
editable_properties.append(ep)
return editable_properties
def _create_editable_property(p_type, args_str, params):
if p_type == appconsts.PROP_EXPRESSION:
"""
For expressions we can't do straight input output numerical
conversion so we need a extending class for expression type.
"""
args = propertyparse.args_string_to_args_dict(args_str)
exp_type = args[EXPRESSION_TYPE] # 'exptype' arg missing?. if this fails, it's a bug in filters.xml
creator_func = EDITABLE_PROPERTY_CREATORS[exp_type]
ep = creator_func(params)
else:
ep = EditableProperty(params)
return ep
def get_transition_editable_properties(compositor):
"""
Creates AbstractProperty extending wrappers for all property tuples in
mlttransitions.CompositorTransition.
"""
transition = compositor.transition
editable_properties = []
for i in range(0, len(transition.properties)):
p_name, p_value, p_type = transition.properties[i]
args_str = transition.info.property_args[p_name]
params = (compositor, (p_name, p_value, p_type), i, args_str)
if p_type == mltfilters.PROP_EXPRESSION:
"""
For expressions we can't do straight input output numerical
conversion so we need a extending class for expression type.
"""
args = propertyparse.args_string_to_args_dict(args_str)
exp_type = args[EXPRESSION_TYPE] # 'exptype' arg missing?. if this fails, it's a bug in compositors.xml
creator_func = EDITABLE_PROPERTY_CREATORS[exp_type]
ep = creator_func(params)
else:
ep = TransitionEditableProperty(params)
ep.track = None
ep.clip_index = None
editable_properties.append(ep)
return editable_properties
def get_non_mlt_editable_properties(clip, filter_object, filter_index):
editable_properties = []
for i in range(0, len(filter_object.non_mlt_properties)):
prop = filter_object.non_mlt_properties[i]
p_name, p_value, p_type = prop
args_str = filter_object.info.property_args[p_name]
ep = NonMltEditableProperty(prop, args_str, clip, filter_index, i)
editable_properties.append(ep)
return editable_properties
# -------------------------------------------- property wrappers objs
class AbstractProperty:
"""
A base class for all wrappers of property tuples in
mltfilters.FilterObject.properties array and in
mlttransitions.CompositorObject.transition.properties array.
This class converts input to output using set ranges.
Class also creates args name->value dict used by all extending classes
and has default versions of editor component callbacks.
"""
def __init__(self, args_str):
self.args = propertyparse.args_string_to_args_dict(args_str)
self.track = None # set in creator loops
self.clip_index = None # set in creator loops
self.name = None # mlt property name. set by extending classes
self._set_input_range()
self._set_output_range()
def get_display_name(self):
"""
Parses display name from args display_name value by replacing "!" with " ", a hack
"""
try:
disp_name = self.args[DISPLAY_NAME]
return disp_name.replace("!"," ") # We're using space as separator in args
# so names with spaces use letter ! in places where spaces go
except:
return self.name
def _set_input_range(self):
try:
range_in = self.args[RANGE_IN]
except: # not defined, use default
range_in = NORMALIZED_FLOAT
if len(range_in.split(",")) == 2: # comma separated range
vals = range_in.split(",")
self.input_range = (propertyparse.get_args_num_value(vals[0]),
propertyparse.get_args_num_value(vals[1]))
elif range_in == NORMALIZED_FLOAT:
self.input_range = (0.0, 1.0)
def _set_output_range(self):
try:
range_out = self.args[RANGE_OUT]
except: # not defined, use default
range_out = NORMALIZED_FLOAT
if len(range_out.split(",")) == 2: # comma separeated range
vals = range_out.split(",")
self.output_range = (propertyparse.get_args_num_value(vals[0]),
propertyparse.get_args_num_value(vals[1]))
elif range_out == NORMALIZED_FLOAT:
self.output_range = (0.0, 1.0)
def get_out_value(self, in_value):
"""
Converts input value to output value using ranges.
"""
in_l, in_h = self.input_range
out_l, out_h = self.output_range
in_range = in_h - in_l
out_range = out_h - out_l
in_frac = in_value - in_l
in_norm = in_frac / in_range
return out_l + (in_norm * out_range)
def get_current_in_value(self):
"""
Corresponding input value for current self.value
"""
return self.get_in_value(float(self.value))
def get_in_value(self, out_value):
"""
Converts output to input value
"""
in_l, in_h = self.input_range
out_l, out_h = self.output_range
in_range = in_h - in_l
out_range = out_h - out_l
out_frac = propertyparse.get_args_num_value(str(out_value)) - out_l
out_norm = out_frac / out_range
return in_l + (out_norm * in_range)
def get_input_range_adjustment(self):
try:
step = propertyparse.get_args_num_value(self.args[STEP])
except:
step = DEFAULT_STEP
lower, upper = self.input_range
value = self.get_current_in_value()
return gtk.Adjustment(float(value), float(lower), float(upper), float(step))
def adjustment_value_changed(self, adjustment):
value = adjustment.get_value()
out_value = self.get_out_value(value)
str_value = str(out_value)
self.write_value(str_value)
def boolean_button_toggled(self, button):
if button.get_active():
val = "1"
else:
val = "0"
self.write_value(val)
def color_selected(self, color_button):
print "color_selected() not overridden"
def combo_selection_changed(self, combo_box, values):
value = values[combo_box.get_active()]
self.write_value(str(value))
def write_value(self, val):
"""
This has to be overridden by all extending classes.
"""
print "write_value() not overridden"
def write_out_keyframes(self, keyframes):
"""
This has to be overridden by extending classes
edited with keyframe editor.
"""
print "write_out_keyframes() not overridden"
def get_clip_length(self):
return self.clip.clip_out - self.clip.clip_in + 1
def get_clip_tline_pos(self):
return self.track.clip_start(self.clip_index)
def update_clip_index(self):
self.clip_index = self.track.clips.index(self.clip)
def get_pixel_aspect_ratio(self):
return (float(current_sequence().profile.sample_aspect_num()) /
current_sequence().profile.sample_aspect_den())
class EditableProperty(AbstractProperty):
"""
A wrapper for mltfilter.FilterObject.properties array property tuple
and related data that converts user input to
property values.
This class is used for properties of type PROP_INT and PROP_FLOAT.
If property type is PROP_EXPRESSION an extending class is used
to parse value expression from input.
"""
def __init__(self, create_params):
"""
property is tuple from FilterObject.properties array.
args_str is args attribute value from filters.xml.
"""
clip, filter_index, prop, property_index, args_str = create_params
AbstractProperty.__init__(self, args_str)
self.name, self.value, self.type = prop
self.clip = clip
self.filter_index = filter_index #index of param in clip.filters, clip created in sequence.py
self.property_index = property_index # index of property in FilterObject.properties. This is the persistant object
self.is_compositor_filter = False # This is after changed after creation if needed
def _get_filter_object(self):
"""
Filter being edited is in different places for normal filters
and filters that are part of compositors
"""
if self.is_compositor_filter:
return self.clip.compositor.filter
else:
return self.clip.filters[self.filter_index]
def write_value(self, str_value): # overrides ConvertingProperty.write_value(str_value)
self.write_mlt_property_str_value(str_value)
self.value = str_value
self.write_filter_object_property(str_value)
def write_mlt_property_str_value(self, str_value):
# mlt property value
filter_object = self._get_filter_object()
filter_object.mlt_filter.set(str(self.name), str(str_value))
def write_filter_object_property(self, str_value):
# Persistant python object
filter_object = self._get_filter_object()
prop = (str(self.name), str(str_value), self.type)
filter_object.properties[self.property_index] = prop
class TransitionEditableProperty(AbstractProperty):
"""
A wrapper for mlttransitions.CompositorObject.transition.properties
array property tuple and related data that converts user input to
property values.
This class is used for properties of type PROP_INT and PROP_FLOAT.
If property type is PROP_EXPRESSION an extending class is used
to parse value expression from input.
"""
def __init__(self, create_params):
clip, prop, property_index, args_str = create_params
AbstractProperty.__init__(self, args_str)
self.name, self.value, self.type = prop
self.clip = clip # this is actually compositor ducktyping for clip
self.transition = clip.transition # ... is compositor.transition
self.property_index = property_index # index of property in mlttransitions.CompositorObject.transition.properties.
# This is the persistant object
def get_clip_tline_pos(self):
# self.clip is actually compositor ducktyping for clip
return self.clip.clip_in # compositor in and out points staright in timeline frames
def write_value(self, str_value):
self.write_mlt_property_str_value(str_value)
self.value = str_value
self.write_transition_object_property(str_value)
def write_mlt_property_str_value(self, str_value):
self.transition.mlt_transition.set(str(self.name), str(str_value))
def write_transition_object_property(self, str_value):
# Persistant python object
prop = (str(self.name), str(str_value), self.type)
self.transition.properties[self.property_index] = prop
class NonMltEditableProperty(AbstractProperty):
"""
A wrapper for editable persistent properties that do not write out values to MLT objects.
Values of these are used to compute valuse that _are_ written to MLT.
"""
def __init__(self, prop, args_str, clip, filter_index, non_mlt_property_index):
AbstractProperty.__init__(self, args_str)
self.name, self.value, self.type = prop
self.clip = clip
self.filter_index = filter_index
self.non_mlt_property_index = non_mlt_property_index
self.adjustment_listener = None # External listener that may be monkeypathched here
def adjustment_value_changed(self, adjustment):
if self.adjustment_listener != None:
value = adjustment.get_value()
out_value = self.get_out_value(value)
self.adjustment_listener(self, out_value)
def _get_filter_object(self):
return self.clip.filters[self.filter_index]
def write_number_value(self, numb):
self.write_property_value(str(numb))
def write_property_value(self, str_value):
filter_object = self._get_filter_object()
prop = (str(self.name), str(str_value), self.type)
filter_object.non_mlt_properties[self.non_mlt_property_index] = prop
self.value = str_value
def get_float_value(self):
return float(self.value)
# ----------------------------------------- PROP_EXPRESSION types extending classes
class SingleKeyFrameProperty(EditableProperty):
"""
Converts adjustments to expressions like "0=value" and
crates adjustments from expressions.
"""
def get_input_range_adjustment(self):
try:
step = propertyparse.get_args_num_value(self.args[STEP])
except:
step = DEFAULT_STEP
lower, upper = self.input_range
val = self.value.strip('"')
epxr_sides = val.split("=")
in_value = self.get_in_value(float(epxr_sides[1]))
return gtk.Adjustment(float(in_value), float(lower), float(upper), float(step))
def adjustment_value_changed(self, adjustment):
value = adjustment.get_value()
out_value = self.get_out_value(value)
val_str = "0=" + str(out_value)
self.write_value(val_str)
class AffineFilterGeomProperty(EditableProperty):
"""
Converts values of four sliders to position and size info
"""
def slider_values_changed(self, all_sliders, w):
x_s, y_s, h_s = all_sliders
x = x_s.get_adjustment().get_value()
y = y_s.get_adjustment().get_value()
h = h_s.get_adjustment().get_value()
# "0=x/y:widthxheight:opacity"
val_str = "0=" + str(x) + "/" + str(y) + ":" + str(w) + "x" + str(h) + ":100" # 100x MLT ignores width
self.write_value(val_str)
class FreiPosHCSFilterProperty(EditableProperty):
def adjustment_value_changed(self, adjustment):
value = adjustment.get_value()
out_value = self.get_out_value(value)
val_str = "0=" + str(out_value)
self.write_value(val_str)
class OpacityInGeomSKFProperty(TransitionEditableProperty):
"""
Converts adjustments to expressions like "0/0:720x576:76" for
opacity of 76% and creates adjustments from expressions.
Only opacity part is edited.
"""
def __init__(self, params):
TransitionEditableProperty.__init__(self, params)
clip, property, property_index, args_str = params
name, value, type = property
self.value_parts = value.split(":")
def get_input_range_adjustment(self):
try:
step = propertyparse.get_args_num_value(self.args[STEP])
except:
step = DEFAULT_STEP
lower, upper = self.input_range
in_value = self.get_in_value(float(self.value_parts[2]))
return gtk.Adjustment(float(in_value), float(lower), float(upper), float(step))
def adjustment_value_changed(self, adjustment):
value = adjustment.get_value()
out_value = self.get_out_value(value)
val_str = self.value_parts[0] + ":" + self.value_parts[1] + ":" + str(out_value)
self.write_value(val_str)
class OpacityInGeomKeyframeProperty(TransitionEditableProperty):
def __init__(self, params):
TransitionEditableProperty.__init__(self, params)
clip, property, property_index, args_str = params
name, value, type = property
# We need values of first keyframe for later
key_frames = value.split(";")
self.value_parts = key_frames[0].split(":")
self.screen_size_str = self.value_parts[1]
def get_input_range_adjustment(self):
# initial opacity value
try:
step = propertyparse.get_args_num_value(self.args[STEP])
except:
step = DEFAULT_STEP
lower, upper = self.input_range
in_value = self.get_in_value(float(self.value_parts[2]))
return gtk.Adjustment(float(in_value), float(lower), float(upper), float(step))
def write_out_keyframes(self, keyframes):
# key frame array of tuples (frame, opacity)
val_str = ""
for kf in keyframes:
frame, opac = kf
val_str += str(int(frame)) + "=" # frame
val_str += "0/0:" # pos
val_str += str(self.screen_size_str) + ":" # size
val_str += str(self.get_out_value(opac)) + ";" # opac with converted range from slider
val_str = val_str.strip(";")
self.write_value(val_str)
class LUTTableProperty(EditableProperty):
def reset_to_linear(self):
self.write_value("LINEAR")
def write_out_table(self, table):
l = []
for i in range(0, len(table)):
l.append(str(table[i]))
l.append(";")
val_str = ''.join(l).rstrip(";")
self.write_value(val_str)
class PointsListProperty(EditableProperty):
def set_value_from_cr_points(self, crpoints):
val_str = ""
for i in range(0, len(crpoints)):
p = crpoints[i]
val_str = val_str + str(p.x) + "/" + str(p.y)
if i < len(crpoints) - 1:
val_str = val_str + ";"
self.write_value(val_str)
class KeyFrameGeometryOpacityProperty(TransitionEditableProperty):
"""
Converts user edits to expressions like "12=11/21:720x576:76" for
to keyframes for position scale and opacity.
"""
def __init__(self, params):
TransitionEditableProperty.__init__(self, params)
def get_input_range_adjustment(self):
# This is used for opacity slider
try:
step = propertyparse.get_args_num_value(self.args[STEP])
except:
step = DEFAULT_STEP
lower, upper = self.input_range
return gtk.Adjustment(float(1.0), float(lower), float(upper), float(step)) # Value set later to first kf value
def write_out_keyframes(self, keyframes):
# key frame array of tuples (frame, [x, y, width, height], opacity)
val_str = ""
for kf in keyframes:
frame, rect, opac = kf
val_str += str(int(frame)) + "=" # frame
val_str += str(int(rect[0])) + "/" + str(int(rect[1])) + ":" # pos
val_str += str(int(rect[2])) + "x" + str(int(rect[3])) + ":" # size
val_str += str(self.get_out_value(opac)) + ";" # opac with converted range from slider
val_str = val_str.strip(";")
self.write_value(val_str)
class FreiGeomHCSTransitionProperty(TransitionEditableProperty):
def __init__(self, params):
TransitionEditableProperty.__init__(self, params)
class KeyFrameHCSFilterProperty(EditableProperty):
"""
Coverts array of keyframe tuples to string of type "0=0.2;123=0.143"
"""
def get_input_range_adjustment(self):
try:
step = propertyparse.get_args_num_value(self.args[STEP])
except:
step = DEFAULT_STEP
lower, upper = self.input_range
return gtk.Adjustment(float(0.1), float(lower), float(upper), float(step)) # Value set later to first kf value
def write_out_keyframes(self, keyframes):
val_str = ""
for kf in keyframes:
frame, val = kf
val_str += str(frame) + "=" + str(self.get_out_value(val)) + ";"
val_str = val_str.strip(";")
self.write_value(val_str)
class KeyFrameHCSTransitionProperty(TransitionEditableProperty):
"""
Coverts array of keyframe tuples to string of type "0=0.2;123=0.143"
"""
def __init__(self, params):
TransitionEditableProperty.__init__(self, params)
def get_input_range_adjustment(self):
try:
step = propertyparse.get_args_num_value(self.args[STEP])
except:
step = DEFAULT_STEP
lower, upper = self.input_range
return gtk.Adjustment(float(0.1), float(lower), float(upper), float(step)) # Value set later to first kf value
def write_out_keyframes(self, keyframes):
val_str = ""
for kf in keyframes:
frame, val = kf
val_str += str(frame) + "=" + str(self.get_out_value(val)) + ";"
val_str = val_str.strip(";")
self.write_value(val_str)
class ColorProperty(EditableProperty):
"""
Gives value as gdk color for gui and writes out color as
different type of hex to mlt
"""
def get_value_as_gdk_color(self):
raw_r, raw_g, raw_b = utils.hex_to_rgb(self.value)
return gtk.gdk.Color(red=(float(raw_r)/255.0),
green=(float(raw_g)/255.0),
blue=(float(raw_b)/255.0))
def color_selected(self, color_button):
color = color_button.get_color()
value = utils.hex_to_rgb(color.to_string())
raw_r, raw_g, raw_b = value
val_str = "#" + utils.int_to_hex(int((float(raw_r) * 255.0) / 65535.0)) + \
utils.int_to_hex(int((float(raw_g) * 255.0) / 65535.0)) + \
utils.int_to_hex(int((float(raw_b) * 255.0) / 65535.0))
self.write_value(val_str)
class WipeResourceProperty(TransitionEditableProperty):
"""
Converts user combobox selections to absolute paths containing wipe
resource images.
"""
def __init__(self, params):
TransitionEditableProperty.__init__(self, params)
def combo_selection_changed(self, combo_box, keys):
key = keys[combo_box.get_active()]
res_path = mlttransitions.get_wipe_resource_path(key)
self.write_value(str(res_path))
class MultipartKeyFrameProperty(AbstractProperty):
def __init__(self, params):
clip, filter_index, property, property_index, args_str = params
AbstractProperty.__init__(self, args_str)
self.name, self.value, self.type = property
self.clip = clip
self.filter_index = filter_index #index of param in clip.filters, clip created in sequence.py
self.property_index = property_index # index of property in FilterObject.properties. This is the persistant object
self.is_compositor_filter = False # This is after changed after creation if needed
def get_input_range_adjustment(self):
try:
step = propertyparse.get_args_num_value(self.args[STEP])
except:
step = DEFAULT_STEP
lower, upper = self.input_range
return gtk.Adjustment(float(0.1), float(lower), float(upper), float(step)) # Value set later to first kf value
def write_out_keyframes(self, keyframes):
val_str = ""
for kf in keyframes:
frame, val = kf
val_str += str(frame) + "=" + str(self.get_out_value(val)) + ";"
val_str = val_str.strip(";")
self.value = val_str
filter_object = self.clip.filters[self.filter_index]
filter_object.update_value(val_str, self.clip, current_sequence().profile)
class AffineScaleProperty(EditableProperty):
def get_input_range_adjustment(self):
step = DEFAULT_STEP
lower = 0
upper = 500
val = self.value.strip('"')
epxr_sides = val.split("=")
in_value = self.get_in_value(float(epxr_sides[1]))
return gtk.Adjustment(float(in_value), float(lower), float(upper), float(step))
def adjustment_value_changed(self, adjustment):
value = adjustment.get_value()
out_value = self.get_out_value(value)
val_str = "0=" + str(out_value)
self.write_value(val_str)
def get_out_value(self, in_value):
"""
Converts input value to output value using ranges.
"""
# in_range = 500 # hard coded special case
in_norm = in_value / 100.0 # to get 0 - 5, 1.0 no scaling
if in_norm < 0.001:
in_norm = 0.001
out = 1 / in_norm
return out
def get_in_value(self, out_value):
"""
Converts output to input value
"""
# out_value = 1 / in_norm, range 1 / 0.001 -> 1 / 5
if out_value < 0.001:
out_value = 0.001
in_value = (1 / (out_value)) * 100 # 0 - 500 range
return in_value
def write_mlt_property_str_value(self, str_value):
val = str_value.strip('"')
epxr_sides = val.split("=")
# mlt property value
filter_object = self._get_filter_object()
filter_object.mlt_filter.set(str(self.name), str(epxr_sides[1]))
# ------------------------------------------ creator func dicts
# dict EXPRESSION_TYPE args value -> class extending AbstractProperty
# Note: HCS means half comma separated
EDITABLE_PROPERTY_CREATORS = { \
DEFAULT:lambda params : EditableProperty(params),
DEFAULT_TRANSITION:lambda params : TransitionEditableProperty(params),
SINGLE_KEYFRAME:lambda params: SingleKeyFrameProperty(params),
OPACITY_IN_GEOM_SINGLE_KF: lambda params : OpacityInGeomSKFProperty(params),
OPACITY_IN_GEOM_KF: lambda params : OpacityInGeomKeyframeProperty(params),
KEYFRAME_HCS: lambda params : KeyFrameHCSFilterProperty(params),
FREI_POSITION_HCS: lambda params : FreiPosHCSFilterProperty(params),
FREI_GEOM_HCS_TRANSITION: lambda params : FreiGeomHCSTransitionProperty(params),
KEYFRAME_HCS_TRANSITION: lambda params : KeyFrameHCSTransitionProperty(params),
MULTIPART_KEYFRAME_HCS: lambda params : MultipartKeyFrameProperty(params),
COLOR: lambda params : ColorProperty(params),
GEOMETRY_OPACITY_KF: lambda params : KeyFrameGeometryOpacityProperty(params),
GEOM_IN_AFFINE_FILTER: lambda params : AffineFilterGeomProperty(params),
WIPE_RESOURCE : lambda params : WipeResourceProperty(params),
LUT_TABLE : lambda params : LUTTableProperty(params),
NOT_PARSED : lambda params : EditableProperty(params), # This should only be used with params that have editor=NO_EDITOR
NOT_PARSED_TRANSITION : lambda params : TransitionEditableProperty(params), # This should only be used with params that have editor=NO_EDITOR
AFFINE_SCALE : lambda params : AffineScaleProperty(params) }
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2014 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
import gtk
import commands
import dbus
import os
import threading
import time
import appconsts
import dialogutils
import editorpersistance
import editorstate
import guiutils
import utils
_jack_frequencies = [22050, 32000, 44100, 48000, 88200, 96000, 192000]
_jack_failsafe_path = utils.get_hidden_user_dir_path() + "/jack_fail_safe"
_dialog = None
def start_up():
pass
def use_jack_clicked(window):
jackstart_thread = JackStartThread(window)
jackstart_thread.start()
class JackChangeThread(threading.Thread):
def __init__(self, window):
threading.Thread.__init__(self)
self.window = window
class JackStartThread(JackChangeThread):
def run(self):
editorstate.PLAYER().jack_output_on()
time.sleep(1.0)
gtk.gdk.threads_enter()
self.window.set_gui_state()
gtk.gdk.threads_leave()
def frequency_changed(freq_index):
editorpersistance.prefs.jack_frequency = _jack_frequencies[freq_index]
editorpersistance.save()
def start_op_changed(w):
if w.get_active() == True:
editorpersistance.prefs.jack_start_up_op = appconsts.JACK_ON_START_UP_YES
else:
editorpersistance.prefs.jack_start_up_op = appconsts.JACK_ON_START_UP_NO
editorpersistance.save()
def output_type_changed(output_type):
editorpersistance.prefs.jack_output_type = output_type
editorpersistance.save()
def delete_failsafe_file():
try:
os.remove(_jack_failsafe_path)
except:
pass
class JackAudioManagerDialog:
def __init__(self):
self.dialog = gtk.Dialog(_("JACK Audio Manager"), None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(_("Close").encode('utf-8'), gtk.RESPONSE_CLOSE))
start_up_label = gtk.Label(_("Start JACK output on application start-up"))
self.startup_check_button = gtk.CheckButton()
if editorpersistance.prefs.jack_start_up_op == appconsts.JACK_ON_START_UP_YES:
self.startup_check_button.set_active(True)
self.startup_check_button.connect("toggled",
lambda w,e: start_op_changed(w),
None)
start_row = guiutils.get_checkbox_row_box(self.startup_check_button, start_up_label)
self.frequency_select = gtk.combo_box_new_text()
cur_value_index = 0
count = 0
for freq in _jack_frequencies:
self.frequency_select.append_text(str(freq))
if freq == editorpersistance.prefs.jack_frequency:
cur_value_index = count
count = count + 1
self.frequency_select.set_active(cur_value_index)
self.frequency_select.connect("changed",
lambda w,e: frequency_changed(w.get_active()),
None)
freq_row = guiutils.get_two_column_box_right_pad(gtk.Label("JACK frequency Hz:"), self.frequency_select, 190, 15)
self.output_type_select = gtk.combo_box_new_text()
self.output_type_select.append_text(_("Audio"))
self.output_type_select.append_text(_("Sync Master Timecode"))
# Indexes correspond with appconsts.JACK_OUT_AUDIO, appconsts.JACK_OUT_SYNC values
self.output_type_select.set_active(editorpersistance.prefs.jack_output_type)
self.output_type_select.connect("changed",
lambda w,e: output_type_changed(w.get_active()),
None)
output_row = guiutils.get_two_column_box_right_pad(gtk.Label("JACK output type:"), self.output_type_select, 190, 15)
vbox_props = gtk.VBox(False, 2)
vbox_props.pack_start(freq_row, False, False, 0)
vbox_props.pack_start(output_row, False, False, 0)
vbox_props.pack_start(start_row, False, False, 0)
vbox_props.pack_start(guiutils.pad_label(8, 12), False, False, 0)
props_frame = guiutils.get_named_frame(_("Properties"), vbox_props)
self.jack_output_status_value = gtk.Label("<b>OFF</b>")
self.jack_output_status_value.set_use_markup(True)
self.jack_output_status_label = gtk.Label("JACK output is ")
status_row = guiutils.get_centered_box([self.jack_output_status_label, self.jack_output_status_value])
self.dont_use_button = gtk.Button(_("Stop JACK Output"))
self.use_button = gtk.Button(_("Start JACK Output"))
self.use_button.connect("clicked", lambda w: use_jack_clicked(self))
self.dont_use_button.connect("clicked", lambda w: _convert_to_original_media_project())
self.set_gui_state()
c_box_2 = gtk.HBox(True, 8)
c_box_2.pack_start(self.dont_use_button, True, True, 0)
c_box_2.pack_start(self.use_button, True, True, 0)
row2_onoff = gtk.HBox(False, 2)
row2_onoff.pack_start(gtk.Label(), True, True, 0)
row2_onoff.pack_start(c_box_2, False, False, 0)
row2_onoff.pack_start(gtk.Label(), True, True, 0)
vbox_onoff = gtk.VBox(False, 2)
vbox_onoff.pack_start(guiutils.pad_label(12, 4), False, False, 0)
vbox_onoff.pack_start(status_row, False, False, 0)
vbox_onoff.pack_start(guiutils.pad_label(12, 12), False, False, 0)
vbox_onoff.pack_start(row2_onoff, False, False, 0)
onoff_frame = guiutils.get_named_frame(_("Output Status"), vbox_onoff)
# Pane
vbox = gtk.VBox(False, 2)
vbox.pack_start(props_frame, False, False, 0)
vbox.pack_start(onoff_frame, False, False, 0)
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(12, 12, 12, 12)
alignment.add(vbox)
self.dialog.vbox.pack_start(alignment, True, True, 0)
dialogutils.default_behaviour(self.dialog)
self.dialog.connect('response', dialogutils.dialog_destroy)
self.dialog.show_all()
global _dialog
_dialog = self
def set_gui_state(self):
if editorstate.PLAYER().jack_output_filter != None:
self.use_button.set_sensitive(False)
self.dont_use_button.set_sensitive(True)
self.jack_output_status_value.set_text("<b>ON</b>")
self.jack_output_status_value.set_use_markup(True)
else:
self.dont_use_button.set_sensitive(False)
self.use_button.set_sensitive(True)
self.jack_output_status_value.set_text("<b>OFF</b>")
self.jack_output_status_value.set_use_markup(True)
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module handles user actions that are not edits on the current sequence.
Load, save, add media file, etc...
"""
import gobject
import pygtk
pygtk.require('2.0');
import gtk
import glib
import datetime
import md5
import os
from os import listdir
from os.path import isfile, join
import re
import shutil
import time
import threading
import app
import appconsts
import batchrendering
import dialogs
import dialogutils
import gui
import guicomponents
import guiutils
import editevent
import editorstate
from editorstate import current_sequence
from editorstate import current_bin
from editorstate import PROJECT
from editorstate import MONITOR_MEDIA_FILE
import editorpersistance
import movemodes
import persistance
import projectdata
import projectinfogui
import propertyparse
import proxyediting
import render
import rendergui
import sequence
import updater
import utils
save_time = None
save_icon_remove_event_id = None
#--------------------------------------- worker threads
class LoadThread(threading.Thread):
def __init__(self, filename, block_recent_files=False):
self.filename = filename
self.block_recent_files = block_recent_files
threading.Thread.__init__(self)
def run(self):
gtk.gdk.threads_enter()
updater.set_info_icon(gtk.STOCK_OPEN)
dialog = dialogs.load_dialog()
persistance.load_dialog = dialog
gtk.gdk.threads_leave()
ticker = utils.Ticker(_load_pulse_bar, 0.15)
ticker.start_ticker()
old_project = editorstate.project
try:
editorstate.project_is_loading = True
project = persistance.load_project(self.filename)
sequence.set_track_counts(project)
editorstate.project_is_loading = False
except persistance.FileProducerNotFoundError as e:
print "did not find file:", e
self._error_stop(dialog, ticker)
primary_txt = _("Media asset was missing!")
secondary_txt = _("Path of missing asset:") + "\n <b>" + e.value + "</b>\n\n" + \
_("Relative search for replacement file in sub folders of project file failed.") + "\n\n" + \
_("To load the project you will need to either:") + "\n" + \
u"\u2022" + " " + _("Use 'Media Linker' tool to relink media assets to new files, or") + "\n" + \
u"\u2022" + " " + _("Place a file with the same exact name and path on the hard drive")
dialogutils.warning_message(primary_txt, secondary_txt, None, is_info=False)
editorstate.project = old_project # persistance.load_project() changes this,
# we simply change it back as no GUI or other state is yet changed
return
except persistance.ProjectProfileNotFoundError as e:
self._error_stop(dialog, ticker)
primary_txt = _("Profile with Description: '") + e.value + _("' was not found on load!")
secondary_txt = _("It is possible to load the project by creating a User Profile with exactly the same Description\nas the missing profile. ") + "\n\n" + \
_("User Profiles can be created by selecting 'Edit->Profiles Manager'.")
dialogutils.warning_message(primary_txt, secondary_txt, None, is_info=False)
editorstate.project = old_project # persistance.load_project() changes this,
# we simply change it back as no GUI or other state is yet changed
return
gtk.gdk.threads_enter()
dialog.info.set_text(_("Opening"))
gtk.gdk.threads_leave()
time.sleep(0.3)
gtk.gdk.threads_enter()
app.open_project(project)
if self.block_recent_files: # naming flipped ????
editorpersistance.add_recent_project_path(self.filename)
editorpersistance.fill_recents_menu_widget(gui.editor_window.uimanager.get_widget('/MenuBar/FileMenu/OpenRecent'), open_recent_project)
gtk.gdk.threads_leave()
gtk.gdk.threads_enter()
updater.set_info_icon(None)
dialog.destroy()
gtk.gdk.threads_leave()
ticker.stop_ticker()
def _error_stop(self, dialog, ticker):
editorstate.project_is_loading = False
gtk.gdk.threads_enter()
updater.set_info_icon(None)
dialog.destroy()
gtk.gdk.threads_leave()
ticker.stop_ticker()
class AddMediaFilesThread(threading.Thread):
def __init__(self, filenames):
threading.Thread.__init__(self)
self.filenames = filenames
def run(self):
gtk.gdk.threads_enter()
watch = gtk.gdk.Cursor(gtk.gdk.WATCH)
gui.editor_window.window.window.set_cursor(watch)
gtk.gdk.threads_leave()
duplicates = []
succes_new_file = None
filenames = self.filenames
for new_file in filenames:
(folder, file_name) = os.path.split(new_file)
if PROJECT().media_file_exists(new_file):
duplicates.append(file_name)
else:
try:
PROJECT().add_media_file(new_file)
succes_new_file = new_file
except projectdata.ProducerNotValidError as err:
print err.__str__()
dialogs.not_valid_producer_dialog(err.value, gui.editor_window.window)
gtk.gdk.threads_enter()
gui.media_list_view.fill_data_model()
max_val = gui.editor_window.media_scroll_window.get_vadjustment().get_upper()
gui.editor_window.media_scroll_window.get_vadjustment().set_value(max_val)
gtk.gdk.threads_leave()
if succes_new_file != None:
editorpersistance.prefs.last_opened_media_dir = os.path.dirname(succes_new_file)
editorpersistance.save()
# Update editor gui
gtk.gdk.threads_enter()
gui.media_list_view.fill_data_model()
gui.bin_list_view.fill_data_model()
_enable_save()
normal_cursor = gtk.gdk.Cursor(gtk.gdk.LEFT_PTR) #RTL
gui.editor_window.window.window.set_cursor(normal_cursor)
gtk.gdk.threads_leave()
if len(duplicates) > 0:
gobject.timeout_add(10, _duplicates_info, duplicates)
def _duplicates_info(duplicates):
primary_txt = _("Media files already present in project were opened!")
MAX_DISPLAYED_ITEMS = 3
items = MAX_DISPLAYED_ITEMS
if len(duplicates) < MAX_DISPLAYED_ITEMS:
items = len(duplicates)
secondary_txt = _("Files already present:\n\n")
for i in range(0, items):
secondary_txt = secondary_txt + "<b>" + duplicates[i] + "</b>" + "\n"
if len(duplicates) > MAX_DISPLAYED_ITEMS:
secondary_txt = secondary_txt + "\n" + "and " + str(len(duplicates) - MAX_DISPLAYED_ITEMS) + " other items.\n"
secondary_txt = secondary_txt + "\nNo duplicate media items were added to project."
dialogutils.info_message(primary_txt, secondary_txt, gui.editor_window.window)
return False
def _load_pulse_bar():
gtk.gdk.threads_enter()
try:
persistance.load_dialog.progress_bar.pulse()
except:
pass
gtk.gdk.threads_leave()
def _enable_save():
gui.editor_window.uimanager.get_widget("/MenuBar/FileMenu/Save").set_sensitive(True)
# ---------------------------------- project: new, load, save
def new_project():
dialogs.new_project_dialog(_new_project_dialog_callback)
def _new_project_dialog_callback(dialog, response_id, profile_combo, tracks_combo,
tracks_combo_values_list):
v_tracks, a_tracks = tracks_combo_values_list[tracks_combo.get_active()]
if response_id == gtk.RESPONSE_ACCEPT:
app.new_project(profile_combo.get_active(), v_tracks, a_tracks)
dialog.destroy()
project_event = projectdata.ProjectEvent(projectdata.EVENT_CREATED_BY_NEW_DIALOG, None)
PROJECT().events.append(project_event)
else:
dialog.destroy()
def load_project():
dialogs.load_project_dialog(_load_project_dialog_callback)
def _load_project_dialog_callback(dialog, response_id):
if response_id == gtk.RESPONSE_ACCEPT:
filenames = dialog.get_filenames()
dialog.destroy()
actually_load_project(filenames[0])
else:
dialog.destroy()
def close_project():
dialogs.close_confirm_dialog(_close_dialog_callback, app.get_save_time_msg(), gui.editor_window.window, editorstate.PROJECT().name)
def _close_dialog_callback(dialog, response_id):
dialog.destroy()
if response_id == gtk.RESPONSE_CLOSE:# "Don't Save"
pass
elif response_id == gtk.RESPONSE_YES:# "Save"
if editorstate.PROJECT().last_save_path != None:
persistance.save_project(editorstate.PROJECT(), editorstate.PROJECT().last_save_path)
else:
dialogutils.warning_message(_("Project has not been saved previously"),
_("Save project with File -> Save As before closing."),
gui.editor_window.window)
return
else: # "Cancel"
return
# This is the same as opening default project
sequence.AUDIO_TRACKS_COUNT = 4
sequence.VIDEO_TRACKS_COUNT = 5
new_project = projectdata.get_default_project()
app.open_project(new_project)
def actually_load_project(filename, block_recent_files=False):
load_launch = LoadThread(filename, block_recent_files)
load_launch.start()
def save_project():
if PROJECT().last_save_path == None:
save_project_as()
else:
_save_project_in_last_saved_path()
def _save_project_in_last_saved_path():
updater.set_info_icon(gtk.STOCK_SAVE)
PROJECT().events.append(projectdata.ProjectEvent(projectdata.EVENT_SAVED, PROJECT().last_save_path))
persistance.save_project(PROJECT(), PROJECT().last_save_path) #<----- HERE
global save_icon_remove_event_id
save_icon_remove_event_id = gobject.timeout_add(500, remove_save_icon)
global save_time
save_time = time.clock()
projectinfogui.update_project_info()
def save_project_as():
if PROJECT().last_save_path != None:
open_dir = os.path.dirname(PROJECT().last_save_path)
else:
open_dir = None
dialogs.save_project_as_dialog(_save_as_dialog_callback, PROJECT().name, open_dir)
def _save_as_dialog_callback(dialog, response_id):
if response_id == gtk.RESPONSE_ACCEPT:
filenames = dialog.get_filenames()
PROJECT().last_save_path = filenames[0]
PROJECT().name = os.path.basename(filenames[0])
updater.set_info_icon(gtk.STOCK_SAVE)
if len(PROJECT().events) == 0: # Save as... with 0 project events is considered Project creation
p_event = projectdata.ProjectEvent(projectdata.EVENT_CREATED_BY_SAVING, PROJECT().last_save_path)
PROJECT().events.append(p_event)
else:
p_event = projectdata.ProjectEvent(projectdata.EVENT_SAVED_AS, (PROJECT().name, PROJECT().last_save_path))
PROJECT().events.append(p_event)
persistance.save_project(PROJECT(), PROJECT().last_save_path) #<----- HERE
app.stop_autosave()
app.start_autosave()
global save_icon_remove_event_id
save_icon_remove_event_id = gobject.timeout_add(500, remove_save_icon)
global save_time
save_time = time.clock()
gui.editor_window.window.set_title(PROJECT().name + " - Flowblade")
gui.editor_window.uimanager.get_widget("/MenuBar/FileMenu/Save").set_sensitive(False)
gui.editor_window.uimanager.get_widget("/MenuBar/EditMenu/Undo").set_sensitive(False)
gui.editor_window.uimanager.get_widget("/MenuBar/EditMenu/Redo").set_sensitive(False)
editorpersistance.add_recent_project_path(PROJECT().last_save_path)
editorpersistance.fill_recents_menu_widget(gui.editor_window.uimanager.get_widget('/MenuBar/FileMenu/OpenRecent'), open_recent_project)
projectinfogui.update_project_info()
dialog.destroy()
else:
dialog.destroy()
def save_backup_snapshot():
parts = PROJECT().name.split(".")
name = parts[0] + datetime.datetime.now().strftime("-%y%m%d") + ".flb"
dialogs.save_backup_snapshot(name, _save_backup_snapshot_dialog_callback)
def _save_backup_snapshot_dialog_callback(dialog, response_id, project_folder, name_entry):
if response_id == gtk.RESPONSE_ACCEPT:
root_path = project_folder.get_filenames()[0]
if not (os.listdir(root_path) == []):
dialog.destroy()
primary_txt = _("Selected folder contains files")
secondary_txt = _("When saving a back-up snapshot of the project, the selected folder\nhas to be empty.")
dialogutils.info_message(primary_txt, secondary_txt, gui.editor_window.window)
return
name = name_entry.get_text()
dialog.destroy()
glib.idle_add(lambda : _do_snapshot_save(root_path + "/", name))
else:
dialog.destroy()
def _do_snapshot_save(root_folder_path, project_name):
save_thread = SnaphotSaveThread(root_folder_path, project_name)
save_thread.start()
class SnaphotSaveThread(threading.Thread):
def __init__(self, root_folder_path, project_name):
self.root_folder_path = root_folder_path
self.project_name = project_name
threading.Thread.__init__(self)
def run(self):
copy_txt = _("Copying project media assets")
project_txt = _("Saving project file")
gtk.gdk.threads_enter()
dialog = dialogs.save_snaphot_progess(copy_txt, project_txt)
gtk.gdk.threads_leave()
media_folder = self.root_folder_path + "media/"
d = os.path.dirname(media_folder)
os.mkdir(d)
asset_paths = {}
# Copy media files
for idkey, media_file in PROJECT().media_files.items():
if media_file.type == appconsts.PATTERN_PRODUCER:
continue
# Copy asset file and fix path
directory, file_name = os.path.split(media_file.path)
gtk.gdk.threads_enter()
dialog.media_copy_info.set_text(copy_txt + "... " + file_name)
gtk.gdk.threads_leave()
media_file_copy = media_folder + file_name
if media_file_copy in asset_paths: # Create different filename for files
# that have same filename but different path
file_name = get_snapshot_unique_name(media_file.path, file_name)
media_file_copy = media_folder + file_name
shutil.copyfile(media_file.path, media_file_copy)
asset_paths[media_file.path] = media_file_copy
# Copy clip producers paths
for seq in PROJECT().sequences:
for track in seq.tracks:
for i in range(0, len(track.clips)):
clip = track.clips[i]
# Only producer clips are affected
if (clip.is_blanck_clip == False and (clip.media_type != appconsts.PATTERN_PRODUCER)):
directory, file_name = os.path.split(clip.path)
clip_file_copy = media_folder + file_name
if not os.path.isfile(clip_file_copy):
directory, file_name = os.path.split(clip.path)
gtk.gdk.threads_enter()
dialog.media_copy_info.set_text(copy_txt + "... " + file_name)
gtk.gdk.threads_leave()
shutil.copyfile(clip.path, clip_file_copy) # only rendered files are copied here
asset_paths[clip.path] = clip_file_copy # This stuff is already md5 hashed, so no duplicate problems here
for compositor in seq.compositors:
if compositor.type_id == "##wipe": # Wipe may have user luma and needs to be looked up relatively
copy_comp_resourse_file(compositor, "resource", media_folder)
if compositor.type_id == "##region": # Wipe may have user luma and needs to be looked up relatively
copy_comp_resourse_file(compositor, "composite.luma", media_folder)
gtk.gdk.threads_enter()
dialog.media_copy_info.set_text(copy_txt + " " + u"\u2713")
gtk.gdk.threads_leave()
save_path = self.root_folder_path + self.project_name
persistance.snapshot_paths = asset_paths
persistance.save_project(PROJECT(), save_path)
persistance.snapshot_paths = None
gtk.gdk.threads_enter()
dialog.saving_project_info.set_text(project_txt + " " + u"\u2713")
gtk.gdk.threads_leave()
time.sleep(2)
gtk.gdk.threads_enter()
dialog.destroy()
gtk.gdk.threads_leave()
project_event = projectdata.ProjectEvent(projectdata.EVENT_SAVED_SNAPSHOT, self.root_folder_path)
PROJECT().events.append(project_event)
gtk.gdk.threads_enter()
projectinfogui.update_project_info()
gtk.gdk.threads_leave()
def get_snapshot_unique_name(file_path, file_name):
(name, ext) = os.path.splitext(file_name)
return md5.new(file_path).hexdigest() + ext
def copy_comp_resourse_file(compositor, res_property, media_folder):
res_path = propertyparse.get_property_value(compositor.transition.properties, res_property)
directory, file_name = os.path.split(res_path)
res_file_copy = media_folder + file_name
if not os.path.isfile(res_file_copy):
shutil.copyfile(res_path, res_file_copy)
def remove_save_icon():
gobject.source_remove(save_icon_remove_event_id)
updater.set_info_icon(None)
def open_recent_project(widget, index):
path = editorpersistance.recent_projects.projects[index]
if not os.path.exists(path):
editorpersistance.recent_projects.projects.pop(index)
editorpersistance.fill_recents_menu_widget(gui.editor_window.uimanager.get_widget('/MenuBar/FileMenu/OpenRecent'), open_recent_project)
primary_txt = _("Project not found on disk")
secondary_txt = _("Project can't be loaded.")
dialogutils.info_message(primary_txt, secondary_txt, gui.editor_window.window)
return
actually_load_project(path)
# ---------------------------------- rendering
def do_rendering():
editevent.insert_move_mode_pressed()
render.render_timeline()
def add_to_render_queue():
args_vals_list = render.get_args_vals_list_for_current_selections()
render_path = render.get_file_path()
# Get render start and end points
if render.widgets.range_cb.get_active() == 0:
start_frame = 0
end_frame = -1 # renders till finish
else:
start_frame = current_sequence().tractor.mark_in
end_frame = current_sequence().tractor.mark_out
# Only do if range defined.
if start_frame == -1 or end_frame == -1:
if render.widgets.range_cb.get_active() == 1:
rendergui.no_good_rander_range_info()
return
# Create render data object
if render.widgets.args_panel.use_args_check.get_active() == False:
enc_index = render.widgets.encoding_panel.encoding_selector.widget.get_active()
quality_index = render.widgets.encoding_panel.quality_selector.widget.get_active()
user_args = False
else: # This is not implemented
enc_index = render.widgets.encoding_panel.encoding_selector.widget.get_active()
quality_index = render.widgets.encoding_panel.quality_selector.widget.get_active()
user_args = False
profile = render.get_current_profile()
profile_text = guicomponents.get_profile_info_text(profile)
fps = profile.fps()
profile_name = profile.description()
r_data = batchrendering.RenderData(enc_index, quality_index, user_args, profile_text, profile_name, fps)
# Add item
try:
batchrendering.add_render_item(PROJECT(),
render_path,
args_vals_list,
start_frame,
end_frame,
r_data)
except Exception as e:
primary_txt = _("Adding item to render queue failed!")
secondary_txt = _("Error message: ") + str(e)
dialogutils.warning_message(primary_txt, secondary_txt, gui.editor_window.window, is_info=False)
return
#primary_txt = "New Render Item File Added to Queue"
#secondary_txt = "Select <b>'Render->Batch Render Queue'</b> from menu\nto launch render queue application.\n" #Press <b>'Reload Queue'</b> button to load new item\ninto queue if application already running."
#dialogutils.info_message(primary_txt, secondary_txt, gui.editor_window.window)
# ----------------------------------- media files
def add_media_files(this_call_is_retry=False):
"""
User selects a media file to added to current bin.
"""
# User neds to select thumbnail folder when promted to complete action
if editorpersistance.prefs.thumbnail_folder == None:
if this_call_is_retry == True:
return
dialogs.select_thumbnail_dir(select_thumbnail_dir_callback, gui.editor_window.window, os.path.expanduser("~"), True)
return
dialogs.media_file_dialog(_("Open.."), _open_files_dialog_cb, True)
def _open_files_dialog_cb(file_select, response_id):
filenames = file_select.get_filenames()
file_select.destroy()
if response_id != gtk.RESPONSE_OK:
return
if len(filenames) == 0:
return
add_media_thread = AddMediaFilesThread(filenames)
add_media_thread.start()
def add_image_sequence():
dialogs.open_image_sequence_dialog(_add_image_sequence_callback, gui.editor_window.window)
def _add_image_sequence_callback(dialog, response_id, data):
if response_id == gtk.RESPONSE_CANCEL:
dialog.destroy()
return
file_chooser, spin = data
frame_file = file_chooser.get_filename()
dialog.destroy()
if frame_file == None:
dialogutils.info_message(_("No file was selected"), _("Select a numbered file to add an Image Sequence to Project."), gui.editor_window.window)
return
(folder, file_name) = os.path.split(frame_file)
try:
number_parts = re.findall("[0-9]+", file_name)
number_part = number_parts[-1] # we want the last number part
except:
dialogutils.info_message(_("Not a sequence file!"), _("Selected file does not have a number part in it,\nso it can't be an image sequence file."), gui.editor_window.window)
return
# Create resource name with MLT syntax for MLT producer
number_index = file_name.find(number_part)
path_name_part = file_name[0:number_index]
end_part = file_name[number_index + len(number_part):len(file_name)]
# The better version with "?begin=xxx" only available after 0.8.7
if editorstate.mlt_version_is_equal_or_greater("0.8.5"):
resource_name_str = path_name_part + "%" + "0" + str(len(number_part)) + "d" + end_part + "?begin=" + number_part
else:
resource_name_str = path_name_part + "%" + "0" + str(len(number_part)) + "d" + end_part
# detect highest file
# FIX: this fails if two similarily numbered sequences in same dir and both have same substring in frame name
onlyfiles = [ f for f in listdir(folder) if isfile(join(folder,f)) ]
highest_number_part = int(number_part)
for f in onlyfiles:
try:
file_number_part = int(re.findall("[0-9]+", f)[-1]) # -1, we want the last number part
except:
continue
if f.find(path_name_part) == -1:
continue
if file_number_part > highest_number_part:
highest_number_part = file_number_part
dialog.destroy()
resource_path = folder + "/" + resource_name_str
length = highest_number_part - int(number_part)
PROJECT().add_image_sequence_media_object(resource_path, file_name + "(img_seq)", length)
gui.media_list_view.fill_data_model()
gui.bin_list_view.fill_data_model()
def open_rendered_file(rendered_file_path):
add_media_thread = AddMediaFilesThread([rendered_file_path])
add_media_thread.start()
def select_thumbnail_dir_callback(dialog, response_id, data):
file_select, retry_add_media = data
folder = file_select.get_filenames()[0]
dialog.destroy()
if response_id == gtk.RESPONSE_YES:
if folder == os.path.expanduser("~"):
dialogutils.warning_message(_("Can't make home folder thumbnails folder"),
_("Please create and select some other folder then \'") +
os.path.expanduser("~") + _("\' as thumbnails folder"),
gui.editor_window.window)
else:
editorpersistance.prefs.thumbnail_folder = folder
editorpersistance.save()
if retry_add_media == True:
add_media_files(True)
def select_render_clips_dir_callback(dialog, response_id, file_select):
folder = file_select.get_filenames()[0]
dialog.destroy()
if response_id == gtk.RESPONSE_YES:
if folder == os.path.expanduser("~"):
dialogs.rendered_clips_no_home_folder_dialog()
else:
editorpersistance.prefs.render_folder = folder
editorpersistance.save()
def delete_media_files(force_delete=False):
"""
Deletes media file. Does not take into account if clips made from
media file are still in sequence.(maybe change this)
"""
selection = gui.media_list_view.get_selected_media_objects()
if len(selection) < 1:
return
file_ids = []
bin_indexes = []
# Get:
# - list of integer keys to delete from Project.media_files
# - list of indexes to delete from Bin.file_ids
for media_obj in selection:
file_id = media_obj.media_file.id
file_ids.append(file_id)
bin_indexes.append(media_obj.bin_index)
# If clip is displayed in monitor clear it and disable clip button.
if media_obj.media_file == MONITOR_MEDIA_FILE:
editorstate._monitor_media_file = None
gui.clip_editor_b.set_sensitive(False)
# Check for proxy rendering issues if not forced delete
if not force_delete:
proxy_issues = False
for file_id in file_ids:
media_file = PROJECT().media_files[file_id]
if media_file.has_proxy_file == True:
proxy_issues = True
if media_file.is_proxy_file == True:
proxy_issues = True
if proxy_issues:
dialogs.proxy_delete_warning_dialog(gui.editor_window.window, _proxy_delete_warning_callback)
return
# Delete from bin
bin_indexes.sort()
bin_indexes.reverse()
for i in bin_indexes:
current_bin().file_ids.pop(i)
# Delete from project
for file_id in file_ids:
PROJECT().media_files.pop(file_id)
gui.media_list_view.fill_data_model()
_enable_save()
def _proxy_delete_warning_callback(dialog, response_id):
dialog.destroy()
if response_id == gtk.RESPONSE_OK:
delete_media_files(True)
def display_media_file_rename_dialog(media_file):
dialogs.new_media_name_dialog(media_file_name_edited, media_file)
def media_file_name_edited(dialog, response_id, data):
"""
Sets edited value to liststore and project data.
"""
name_entry, media_file = data
new_text = name_entry.get_text()
dialog.destroy()
if response_id != gtk.RESPONSE_ACCEPT:
return
if len(new_text) == 0:
return
media_file.name = new_text
gui.media_list_view.fill_data_model()
def _display_file_info(media_file):
clip = current_sequence().create_file_producer_clip(media_file.path)
width = clip.get("width")
height = clip.get("height")
size = str(width) + " x " + str(height)
length = utils.get_tc_string(clip.get_length())
try:
img = guiutils.get_gtk_image_from_file(media_file.icon_path, 300)
except:
print "_display_file_info() failed to get thumbnail"
video_index = clip.get_int("video_index")
audio_index = clip.get_int("audio_index")
long_video_property = "meta.media." + str(video_index) + ".codec.long_name"
long_audio_property = "meta.media." + str(audio_index) + ".codec.long_name"
vcodec = clip.get(str(long_video_property))
acodec = clip.get(str(long_audio_property))
frame = clip.get_frame()
channels = str(frame.get_int("channels"))
frequency = str(frame.get_int("frequency")) + "Hz"
try:
num = float(clip.get("meta.media.frame_rate_num")) # from producer_avformat.c
den = float(clip.get("meta.media.frame_rate_den")) # from producer_avformat.c
fps = str(num/den)
except:
fps ="N/A"
dialogs.file_properties_dialog((media_file, img, size, length, vcodec, acodec, channels, frequency, fps))
def remove_unused_media():
# Create path -> media item dict
path_to_media_object = {}
for key, media_item in PROJECT().media_files.items():
if media_item.path != "" and media_item.path != None:
path_to_media_object[media_item.path] = media_item
# Remove all items from created dict that have a clip with same path on any of the sequences
for seq in PROJECT().sequences:
for track in seq.tracks:
for clip in track.clips:
try:
removed = path_to_media_object.pop(clip.path)
print "Removed: " + removed.path
except:
pass
# Create a list of unused media objects
unused = []
for path, media_item in path_to_media_object.items():
unused.append(media_item)
# It is most convenient to do remove via gui object
gui.media_list_view.select_media_file_list(unused)
delete_media_files()
def media_filtering_select_pressed(widget, event):
guicomponents.get_file_filter_popup_menu(widget, event, _media_filtering_selector_item_activated)
def _media_filtering_selector_item_activated(selector, index):
gui.media_view_filter_selector.set_pixbuf(index)
# Const value correspond with indexes here
editorstate.media_view_filter = index
gui.media_list_view.fill_data_model()
# ------------------------------------ bins
def add_new_bin():
"""
Adds new unnamed bin and sets it selected
"""
PROJECT().add_unnamed_bin()
gui.bin_list_view.fill_data_model()
selection = gui.bin_list_view.treeview.get_selection()
model, iterator = selection.get_selected()
selection.select_path(str(len(model)-1))
_enable_save()
def delete_selected_bin():
"""
Deletes current bin if it's empty and at least one will be left.
"""
if len(current_bin().file_ids) != 0:
dialogutils.warning_message(_("Can't remove a non-empty bin"),
_("You must remove all files from the bin before deleting it."),
gui.editor_window.window)
return
# Get iter and index for (current) selected bin
selection = gui.bin_list_view.treeview.get_selection()
model, iter = selection.get_selected()
if len(model) < 2:
dialogutils.warning_message(_("Can't remove last bin"),
_("There must always exist at least one bin."),
gui.editor_window.window)
return
(model, rows) = selection.get_selected_rows()
row = max(rows[0])
# Remove from gui and project data
model.remove(iter)
PROJECT().bins.pop(row)
# Set first bin selected, listener 'bin_selection_changed' updates editorstate.project.c_bin
selection.select_path("0")
_enable_save()
def bin_name_edited(cell, path, new_text, user_data):
"""
Sets edited value to liststore and project data.
"""
# Can't have empty string names
if len(new_text) == 0:
return
liststore, column = user_data
liststore[path][column] = new_text
PROJECT().bins[int(path)].name = new_text
_enable_save()
def bin_selection_changed(selection):
"""
Sets first selected row as current bin and displays media files in it
if we get a selection with contents, empty selections caused by
adding / deleting bins are discarded.
"""
# Get index for selected bin
(model, rows) = selection.get_selected_rows()
if len(rows) == 0:
return
row = max(rows[0])
# Set current and display
PROJECT().c_bin = PROJECT().bins[row]
gui.media_list_view.fill_data_model()
def move_files_to_bin(new_bin, bin_indexes):
# If we're moving clips to bin that they're already in, do nothing.
if PROJECT().bins[new_bin] == current_bin():
return
# Delete from current bin
moved_ids = []
bin_indexes.sort()
bin_indexes.reverse()
for i in bin_indexes:
moved_ids.append(current_bin().file_ids.pop(i))
# Add to target bin
for file_id in moved_ids:
PROJECT().bins[new_bin].file_ids.append(file_id)
gui.media_list_view.fill_data_model()
gui.bin_list_view.fill_data_model()
# ------------------------------------ sequences
def change_edit_sequence():
selection = gui.sequence_list_view.treeview.get_selection()
(model, rows) = selection.get_selected_rows()
row = max(rows[0])
current_index = PROJECT().sequences.index(current_sequence())
if row == current_index:
dialogutils.warning_message(_("Selected sequence is already being edited"),
_("Select another sequence. Press Add -button to create a\nnew sequence if needed."),
gui.editor_window.window)
return
# Clear clips selection at exit. This is transient user focus state and
# therefore is not saved.
movemodes.clear_selected_clips()
app.change_current_sequence(row)
def add_new_sequence():
default_name = _("sequence_") + str(PROJECT().next_seq_number)
dialogs.new_sequence_dialog(_add_new_sequence_dialog_callback, default_name)
def _add_new_sequence_dialog_callback(dialog, response_id, widgets):
"""
Adds new unnamed sequence and sets it selected
"""
if response_id != gtk.RESPONSE_ACCEPT:
dialog.destroy()
return
name_entry, tracks_combo, open_check = widgets
# Get dialog data
name = name_entry.get_text()
if len(name) == 0:
name = _("sequence_") + str(PROJECT().next_seq_number)
v_tracks, a_tracks = appconsts.TRACK_CONFIGURATIONS[tracks_combo.get_active()]
open_right_away = open_check.get_active()
# Get index for selected sequence
selection = gui.sequence_list_view.treeview.get_selection()
(model, rows) = selection.get_selected_rows()
row = max(rows[0])
# Add new sequence
sequence.AUDIO_TRACKS_COUNT = a_tracks
sequence.VIDEO_TRACKS_COUNT = v_tracks
PROJECT().add_named_sequence(name)
gui.sequence_list_view.fill_data_model()
if open_right_away == False:
selection.select_path(str(row)) # Keep previous selection
else:
app.change_current_sequence(len(PROJECT().sequences) - 1)
dialog.destroy()
def delete_selected_sequence():
"""
Deletes selected sequence if confirmed and at least one will be left.
"""
selection = gui.sequence_list_view.treeview.get_selection()
model, iter = selection.get_selected()
(model, rows) = selection.get_selected_rows()
row = max(rows[0])
name = PROJECT().sequences[row].name
dialogutils.warning_confirmation(_delete_confirm_callback,
_("Are you sure you want to delete\nsequence \'") + name + _("\'?"),
_("This operation can not be undone. Sequence will be permanently lost."),
gui.editor_window.window)
def _delete_confirm_callback(dialog, response_id):
if response_id != gtk.RESPONSE_ACCEPT:
dialog.destroy()
return
dialog.destroy()
selection = gui.sequence_list_view.treeview.get_selection()
model, iter = selection.get_selected()
# Have to have one sequence.
if len(model) < 2:
dialogutils.warning_message(_("Can't remove last sequence"),
_("There must always exist at least one sequence."),
gui.editor_window.window)
return
(model, rows) = selection.get_selected_rows()
row = max(rows[0])
current_index = PROJECT().sequences.index(current_sequence())
# Remove sequence from gui and project data
model.remove(iter)
PROJECT().sequences.pop(row)
# If we deleted current sequence, open first sequence
if row == current_index:
app.change_current_sequence(0)
_enable_save()
def sequence_name_edited(cell, path, new_text, user_data):
"""
Sets edited value to liststore and project data.
"""
# Can't have empty string names
if len(new_text) == 0:
return
liststore, column = user_data
liststore[path][column] = new_text
PROJECT().sequences[int(path)].name = new_text
_enable_save()
def change_sequence_track_count():
dialogs.tracks_count_change_dialog(_change_track_count_dialog_callback)
def _change_track_count_dialog_callback(dialog, response_id, tracks_combo):
if response_id != gtk.RESPONSE_ACCEPT:
dialog.destroy()
return
v_tracks, a_tracks = appconsts.TRACK_CONFIGURATIONS[tracks_combo.get_active()]
dialog.destroy()
cur_seq_index = PROJECT().sequences.index(PROJECT().c_seq)
new_seq = sequence.create_sequence_clone_with_different_track_count(PROJECT().c_seq, v_tracks, a_tracks)
PROJECT().sequences.insert(cur_seq_index, new_seq)
PROJECT().sequences.pop(cur_seq_index + 1)
app.change_current_sequence(cur_seq_index)
# --------------------------------------------------------- pop-up menus
def media_file_menu_item_selected(widget, data):
item_id, media_file, event = data
if item_id == "File Properties":
_display_file_info(media_file)
if item_id == "Open in Clip Monitor":
updater.set_and_display_monitor_media_file(media_file)
if item_id == "Render Slow/Fast Motion File":
render.render_frame_buffer_clip(media_file)
if item_id == "Rename":
display_media_file_rename_dialog(media_file)
if item_id == "Delete":
gui.media_list_view.select_media_file(media_file)
delete_media_files()
if item_id == "Render Proxy File":
proxyediting.create_proxy_menu_item_selected(media_file)
def _select_treeview_on_pos_and_return_row_and_column_title(event, treeview):
selection = treeview.get_selection()
path_pos_tuple = treeview.get_path_at_pos(int(event.x), int(event.y))
if path_pos_tuple == None:
return (-1, -1) # Empty row was clicked
path, column, x, y = path_pos_tuple
title = column.get_title()
selection.unselect_all()
selection.select_path(path)
(model, rows) = selection.get_selected_rows()
row = max(rows[0])
return (row, title)
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2014 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
This module handles actions initiated from clip and compositor popup menus.
"""
import audiowaveform
import appconsts
import clipeffectseditor
import compositeeditor
import dialogs
import dialogutils
import gtk
import gui
import guicomponents
import edit
import editevent
from editorstate import current_sequence
from editorstate import get_track
from editorstate import PROJECT
import movemodes
import syncsplitevent
import tlinewidgets
import updater
import utils
# ---------------------------------- clip menu
def display_clip_menu(y, event, frame):
# See if we actually hit a clip
track = tlinewidgets.get_track(y)
if track == None:
return False
clip_index = current_sequence().get_clip_index(track, frame)
if clip_index == -1:
return False
# Can't do anything to clips in locked tracks
if editevent.track_lock_check_and_user_info(track, display_clip_menu, "clip context menu"):
return False
# Display popup
pressed_clip = track.clips[clip_index]
if pressed_clip.is_blanck_clip == False:
movemodes.select_clip(track.id, clip_index)
else:
movemodes.select_blank_range(track, pressed_clip)
if track.type == appconsts.VIDEO:
guicomponents.display_clip_popup_menu(event, pressed_clip, \
track, _clip_menu_item_activated)
elif track.type == appconsts.AUDIO:
guicomponents.display_audio_clip_popup_menu(event, pressed_clip, \
track, _clip_menu_item_activated)
return True
def _clip_menu_item_activated(widget, data):
# Callback from selected clipmenu item
clip, track, item_id, item_data = data
handler = POPUP_HANDLERS[item_id]
handler(data)
def _compositor_menu_item_activated(widget, data):
action_id, compositor = data
if action_id == "open in editor":
compositeeditor.set_compositor(compositor)
elif action_id == "delete":
compositor.selected = False
data = {"compositor":compositor}
action = edit.delete_compositor_action(data)
action.do_edit()
elif action_id == "sync with origin":
track = current_sequence().tracks[compositor.transition.b_track] # b_track is source track where origin clip is
origin_clip = None
for clip in track.clips:
if clip.id == compositor.origin_clip_id:
origin_clip = clip
if origin_clip == None:
dialogutils.info_message(_("Origin clip not found!"),
_("Clip used to create this Compositor has been removed\nor moved to different track."),
gui.editor_window.window)
return
clip_index = track.clips.index(origin_clip)
clip_start = track.clip_start(clip_index)
clip_end = clip_start + origin_clip.clip_out - origin_clip.clip_in
data = {"compositor":compositor,"clip_in":clip_start,"clip_out":clip_end}
action = edit.move_compositor_action(data)
action.do_edit()
def _open_clip_in_effects_editor(data):
updater.open_clip_in_effects_editor(data)
def _open_clip_in_clip_monitor(data):
clip, track, item_id, x = data
media_file = PROJECT().get_media_file_for_path(clip.path)
media_file.mark_in = clip.clip_in
media_file.mark_out = clip.clip_out
updater.set_and_display_monitor_media_file(media_file)
gui.pos_bar.widget.grab_focus()
def _show_clip_info(data):
clip, track, item_id, x = data
width = clip.get("width")
height = clip.get("height")
size = str(width) + " x " + str(height)
l_frames = clip.clip_out - clip.clip_in + 1 # +1 out inclusive
length = utils.get_tc_string(l_frames)
video_index = clip.get_int("video_index")
audio_index = clip.get_int("audio_index")
long_video_property = "meta.media." + str(video_index) + ".codec.long_name"
long_audio_property = "meta.media." + str(audio_index) + ".codec.long_name"
vcodec = clip.get(str(long_video_property))
acodec = clip.get(str(long_audio_property))
dialogs.clip_properties_dialog((length, size, clip.path, vcodec, acodec))
def _rename_clip(data):
clip, track, item_id, x = data
dialogs.new_clip_name_dialog(_rename_clip_edited, clip)
def _rename_clip_edited(dialog, response_id, data):
"""
Sets edited value to liststore and project data.
"""
name_entry, clip = data
new_text = name_entry.get_text()
dialog.destroy()
if response_id != gtk.RESPONSE_ACCEPT:
return
if len(new_text) == 0:
return
clip.name = new_text
updater.repaint_tline()
def _clip_color(data):
clip, track, item_id, clip_color = data
if clip_color == "default":
clip.color = None
elif clip_color == "red":
clip.color = (1, 0, 0)
elif clip_color == "green":
clip.color = (0, 1, 0)
elif clip_color == "blue":
clip.color = (0.2, 0.2, 0.9)
elif clip_color == "orange":
clip.color =(0.929, 0.545, 0.376)
elif clip_color == "brown":
clip.color = (0.521, 0.352, 0.317)
elif clip_color == "olive":
clip.color = (0.5, 0.55, 0.5)
updater.repaint_tline()
def open_selection_in_effects():
if movemodes.selected_range_in == -1:
return
track = get_track(movemodes.selected_track)
clip = track.clips[movemodes.selected_range_in]
clipeffectseditor.set_clip(clip, track, movemodes.selected_range_in)
def _add_filter(data):
clip, track, item_id, item_data = data
x, filter_info = item_data
action = clipeffectseditor.get_filter_add_action(filter_info, clip)
action.do_edit()
# (re)open clip in editor
frame = tlinewidgets.get_frame(x)
index = track.get_clip_index_at(frame)
clipeffectseditor.set_clip(clip, track, index)
def _add_compositor(data):
clip, track, item_id, item_data = data
x, compositor_type = item_data
frame = tlinewidgets.get_frame(x)
clip_index = track.get_clip_index_at(frame)
target_track_index = track.id - 1
compositor_in = current_sequence().tracks[track.id].clip_start(clip_index)
clip_length = clip.clip_out - clip.clip_in
compositor_out = compositor_in + clip_length
edit_data = {"origin_clip_id":clip.id,
"in_frame":compositor_in,
"out_frame":compositor_out,
"a_track":target_track_index,
"b_track":track.id,
"compositor_type":compositor_type}
action = edit.add_compositor_action(edit_data)
action.do_edit()
updater.repaint_tline()
def _mute_clip(data):
clip, track, item_id, item_data = data
set_clip_muted = item_data
if set_clip_muted == True:
data = {"clip":clip}
action = edit.mute_clip(data)
action.do_edit()
else:# then we're stting clip unmuted
data = {"clip":clip}
action = edit.unmute_clip(data)
action.do_edit()
def _delete_blank(data):
clip, track, item_id, x = data
movemodes.select_blank_range(track, clip)
from_index = movemodes.selected_range_in
to_index = movemodes.selected_range_out
movemodes.clear_selected_clips()
data = {"track":track,"from_index":from_index,"to_index":to_index}
action = edit.remove_multiple_action(data)
action.do_edit()
def _cover_blank_from_prev(data):
clip, track, item_id, item_data = data
clip_index = movemodes.selected_range_in - 1
if clip_index < 0: # we're not getting legal clip index
return
cover_clip = track.clips[clip_index]
# Check that clip covers blank area
total_length = 0
for i in range(movemodes.selected_range_in, movemodes.selected_range_out + 1):
total_length += track.clips[i].clip_length()
clip_handle = cover_clip.get_length() - cover_clip.clip_out - 1
if total_length > clip_handle: # handle not long enough to cover blanks
primary_txt = _("Previous clip does not have enough material to cover blank area")
secondary_txt = _("Requested edit can't be done.")
dialogutils.info_message(primary_txt, secondary_txt, gui.editor_window.window)
return
# Do edit
movemodes.clear_selected_clips()
data = {"track":track, "clip":cover_clip, "clip_index":clip_index}
action = edit.trim_end_over_blanks(data)
action.do_edit()
def _cover_blank_from_next(data):
clip, track, item_id, item_data = data
clip_index = movemodes.selected_range_out + 1
blank_index = movemodes.selected_range_in
if clip_index < 0: # we're not getting legal clip index
return
cover_clip = track.clips[clip_index]
# Check that clip covers blank area
total_length = 0
for i in range(movemodes.selected_range_in, movemodes.selected_range_out + 1):
total_length += track.clips[i].clip_length()
if total_length > cover_clip.clip_in: # handle not long enough to cover blanks
primary_txt = _("Next clip does not have enough material to cover blank area")
secondary_txt = _("Requested edit can't be done.")
dialogutils.info_message(primary_txt, secondary_txt, gui.editor_window.window)
return
# Do edit
movemodes.clear_selected_clips()
data = {"track":track, "clip":cover_clip, "blank_index":blank_index}
action = edit.trim_start_over_blanks(data)
action.do_edit()
def clear_filters():
if movemodes.selected_track == -1:
return
track = get_track(movemodes.selected_track)
clips = []
for i in range(movemodes.selected_range_in, movemodes.selected_range_out + 1):
clips.append(track.clips[i])
data = {"clips":clips}
action = edit.remove_multiple_filters_action(data)
action.do_edit()
movemodes.clear_selected_clips()
updater.repaint_tline()
def _display_wavefrom(data):
audiowaveform.set_waveform_displayer_clip_from_popup(data)
def _clear_waveform(data):
audiowaveform.clear_waveform(data)
def _clone_filters_from_next(data):
clip, track, item_id, item_data = data
index = track.clips.index(clip)
if index == len(track.clips) - 1:
return # clip is last clip
clone_clip = track.clips[index + 1]
_do_filter_clone(clip, clone_clip)
def _clone_filters_from_prev(data):
clip, track, item_id, item_data = data
index = track.clips.index(clip)
if index == 0:
return # clip is first clip
clone_clip = track.clips[index - 1]
_do_filter_clone(clip, clone_clip)
def _do_filter_clone(clip, clone_clip):
if clone_clip.is_blanck_clip:
return
data = {"clip":clip,"clone_source_clip":clone_clip}
action = edit.clone_filters_action(data)
action.do_edit()
# Functions to handle popup menu selections for strings
# set as activation messages in guicomponents.py
# activation_message -> _handler_func
POPUP_HANDLERS = {"set_master":syncsplitevent.init_select_master_clip,
"open_in_editor":_open_clip_in_effects_editor,
"clip_info":_show_clip_info,
"open_in_clip_monitor":_open_clip_in_clip_monitor,
"rename_clip":_rename_clip,
"clip_color":_clip_color,
"split_audio":syncsplitevent.split_audio,
"split_audio_synched":syncsplitevent.split_audio_synched,
"resync":syncsplitevent.resync_clip,
"add_filter":_add_filter,
"add_compositor":_add_compositor,
"clear_sync_rel":syncsplitevent.clear_sync_relation,
"mute_clip":_mute_clip,
"display_waveform":_display_wavefrom,
"clear_waveform":_clear_waveform,
"delete_blank":_delete_blank,
"cover_with_prev": _cover_blank_from_prev,
"cover_with_next": _cover_blank_from_next,
"clone_filters_from_next": _clone_filters_from_next,
"clone_filters_from_prev": _clone_filters_from_prev}
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module contains GUI widgets used to edit keyframed properties in filters and
compositors.
NOTE: All the editors are composites of smaller objects (so that similar
but slighly different editors can be made in the future). There are a lots
of callbacks to parent objects, this makes the design difficult to follow.
"""
import copy
import pygtk
pygtk.require('2.0');
import gtk
import math
import pango
from cairoarea import CairoDrawableArea
from editorstate import PLAYER
from editorstate import current_sequence
import gui
import guicomponents
import guiutils
import propertyedit
import propertyparse
import respaths
import utils
import viewgeom
# Draw consts
CLIP_EDITOR_WIDTH = 250
CLIP_EDITOR_HEIGHT = 21
END_PAD = 18
TOP_PAD = 2
BUTTON_WIDTH = 26
BUTTON_HEIGHT = 24
KF_Y = 5
CENTER_LINE_Y = 11
POS_ENTRY_W = 38
POS_ENTRY_H = 20
KF_HIT_WIDTH = 4
KF_DRAG_THRESHOLD = 3
EP_HALF = 4
GEOMETRY_EDITOR_WIDTH = 250
GEOMETRY_EDITOR_HEIGHT = 200
GEOM_EDITOR_SIZE_LARGE = 0.9
GEOM_EDITOR_SIZE_SMALL = 0.3
GEOM_EDITOR_SIZE_MEDIUM = 0.6 # displayed screensize as fraction of available height
GEOM_EDITOR_SIZES = [GEOM_EDITOR_SIZE_LARGE, GEOM_EDITOR_SIZE_MEDIUM, GEOM_EDITOR_SIZE_SMALL]
# Rectangle edit handles ids. Points numbered in clockwise direction
# to get opposite points easily.
TOP_LEFT = 0
TOP_MIDDLE = 1
TOP_RIGHT = 2
MIDDLE_RIGHT = 3
BOTTOM_RIGHT = 4
BOTTOM_MIDDLE = 5
BOTTOM_LEFT = 6
MIDDLE_LEFT = 7
# Rotating rectangle handle ids
POS_HANDLE = 0
X_SCALE_HANDLE = 1
Y_SCALE_HANDLE = 2
ROTATION_HANDLE = 3
# Hit values for rect, edit point hits return edit point id
AREA_HIT = 9
NO_HIT = 10
# Hit values for rotating geom edits, NO_HIT used too
POS_EDIT_HIT = 0
# Colors
POINTER_COLOR = (1, 0.3, 0.3)
CLIP_EDITOR_BG_COLOR = (0.7, 0.7, 0.7)
LIGHT_MULTILPLIER = 1.14
DARK_MULTIPLIER = 0.74
EDITABLE_RECT_COLOR = (0,0,0)
NOT_EDITABLE_RECT_COLOR = (1,0,0)
# Editor states
KF_DRAG = 0
POSITION_DRAG = 1
KF_DRAG_DISABLED = 2
# Icons
ACTIVE_KF_ICON = None
NON_ACTIVE_KF_ICON = None
# Magic value to signify disconnected signal handler
DISCONNECTED_SIGNAL_HANDLER = -9999999
# ----------------------------------------------------- editor objects
class ClipKeyFrameEditor:
"""
GUI component used to add, move and remove keyframes
inside a single clip. It is used as a component inside a parent editor and
needs the parent editor to write out keyframe values.
Parent editor must implement callback interface:
def clip_editor_frame_changed(self, frame)
def active_keyframe_changed(self)
def keyframe_dragged(self, active_kf, frame)
def update_slider_value_display(self, frame)
"""
def __init__(self, editable_property, parent_editor, use_clip_in=True):
self.widget = CairoDrawableArea(CLIP_EDITOR_WIDTH,
CLIP_EDITOR_HEIGHT,
self._draw)
self.widget.press_func = self._press_event
self.widget.motion_notify_func = self._motion_notify_event
self.widget.release_func = self._release_event
self.clip_length = editable_property.get_clip_length() - 1 # -1 added to get correct results, yeah...
# Some filters start keyframes from *MEDIA* frame 0
# Some filters or compositors start keyframes from *CLIP* frame 0
# Filters starting from *MEDIA* 0 need offset
# to clip start added to all values.
self.use_clip_in = use_clip_in
if self.use_clip_in == True:
self.clip_in = editable_property.clip.clip_in
else:
self.clip_in = 0
self.current_clip_frame = self.clip_in
self.keyframes = [(0, 0.0)]
self.active_kf_index = 0
self.parent_editor = parent_editor
self.keyframe_parser = None # Function used to parse keyframes to tuples is different for different expressions
# Parent editor sets this.
self.current_mouse_action = None
self.drag_on = False # Used to stop updating pos here if pos change is initiated here.
self.drag_min = -1
self.drag_max = -1
# init icons if needed
global ACTIVE_KF_ICON, NON_ACTIVE_KF_ICON
if ACTIVE_KF_ICON == None:
ACTIVE_KF_ICON = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "kf_active.png")
if NON_ACTIVE_KF_ICON == None:
NON_ACTIVE_KF_ICON = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "kf_not_active.png")
def set_keyframes(self, keyframes_str, out_to_in_func):
self.keyframes = self.keyframe_parser(keyframes_str, out_to_in_func)
def _get_panel_pos(self):
return self._get_panel_pos_for_frame(self.current_clip_frame)
def _get_panel_pos_for_frame(self, frame):
active_width = self.widget.allocation.width - 2 * END_PAD
disp_frame = frame - self.clip_in
return END_PAD + int((float(disp_frame) / float(self.clip_length)) *
active_width)
def _get_frame_for_panel_pos(self, panel_x):
active_width = self.widget.allocation.width - 2 * END_PAD
clip_panel_x = panel_x - END_PAD
norm_pos = float(clip_panel_x) / float(active_width)
return int(norm_pos * self.clip_length) + self.clip_in
def _set_clip_frame(self, panel_x):
self.current_clip_frame = self._get_frame_for_panel_pos(panel_x)
def move_clip_frame(self, delta):
self.current_clip_frame = self.current_clip_frame + delta
self._force_current_in_frame_range()
def set_and_display_clip_frame(self, clip_frame):
self.current_clip_frame = clip_frame
self._force_current_in_frame_range()
def _draw(self, event, cr, allocation):
"""
Callback for repaint from CairoDrawableArea.
We get cairo context and allocation.
"""
x, y, w, h = allocation
active_width = w - 2 * END_PAD
active_height = h - 2 * TOP_PAD
# Draw bg
cr.set_source_rgb(*(gui.bg_color_tuple))
cr.rectangle(0, 0, w, h)
cr.fill()
# Draw clip bg
cr.set_source_rgb(*CLIP_EDITOR_BG_COLOR)
cr.rectangle(END_PAD, TOP_PAD, active_width, active_height)
cr.fill()
# Clip edge and emboss
rect = (END_PAD, TOP_PAD, active_width, active_height)
self.draw_edge(cr, rect)
self.draw_emboss(cr, rect, gui.bg_color_tuple)
# Draw center line
cr.set_source_rgb(0.4, 0.4, 0.4)
cr.set_line_width(2.0)
cr.move_to(END_PAD, CENTER_LINE_Y)
cr.line_to(END_PAD + active_width, CENTER_LINE_Y)
cr.stroke()
# Draw keyframes
for i in range(0, len(self.keyframes)):
frame, value = self.keyframes[i]
if i == self.active_kf_index:
icon = ACTIVE_KF_ICON
else:
icon = NON_ACTIVE_KF_ICON
try:
kf_pos = self._get_panel_pos_for_frame(frame)
except ZeroDivisionError: # math fails for 1 frame clip
kf_pos = END_PAD
cr.set_source_pixbuf(icon, kf_pos - 6, KF_Y)
cr.paint()
# Draw frame pointer
try:
panel_pos = self._get_panel_pos()
except ZeroDivisionError: # math fails for 1 frame clip
panel_pos = END_PAD
cr.set_line_width(2.0)
cr.set_source_rgb(*POINTER_COLOR)
cr.move_to(panel_pos, 0)
cr.line_to(panel_pos, CLIP_EDITOR_HEIGHT)
cr.stroke()
def draw_emboss(self, cr, rect, color):
# Emboss, corner points
left = rect[0] + 1.5
up = rect[1] + 1.5
right = left + rect[2] - 2.0
down = up + rect[3] - 2.0
# Draw lines
light_color = guiutils.get_multiplied_color(color, LIGHT_MULTILPLIER)
cr.set_source_rgb(*light_color)
cr.move_to(left, down)
cr.line_to(left, up)
cr.stroke()
cr.move_to(left, up)
cr.line_to(right, up)
cr.stroke()
dark_color = guiutils.get_multiplied_color(color, DARK_MULTIPLIER)
cr.set_source_rgb(*dark_color)
cr.move_to(right, up)
cr.line_to(right, down)
cr.stroke()
cr.move_to(right, down)
cr.line_to(left, down)
cr.stroke()
def draw_edge(self, cr, rect):
cr.set_line_width(1.0)
cr.set_source_rgb(0, 0, 0)
cr.rectangle(rect[0] + 0.5, rect[1] + 0.5, rect[2], rect[3])
cr.stroke()
def _press_event(self, event):
"""
Mouse button callback
"""
self.drag_on = True
lx = self._legalize_x(event.x)
hit_kf = self._key_frame_hit(lx, event.y)
if hit_kf == None: # nothing was hit
self.current_mouse_action = POSITION_DRAG
self._set_clip_frame(lx)
self.parent_editor.clip_editor_frame_changed(self.current_clip_frame)
self.widget.queue_draw()
else: # some keyframe was pressed
self.active_kf_index = hit_kf
frame, value = self.keyframes[hit_kf]
self.current_clip_frame = frame
self.parent_editor.active_keyframe_changed()
if hit_kf == 0:
self.current_mouse_action = KF_DRAG_DISABLED
else:
self.current_mouse_action = KF_DRAG
self.drag_start_x = event.x
prev_frame, val = self.keyframes[hit_kf - 1]
self.drag_min = prev_frame + 1
try:
next_frame, val = self.keyframes[hit_kf + 1]
self.drag_max = next_frame - 1
except:
self.drag_max = self.clip_length - 1
self.widget.queue_draw()
def _motion_notify_event(self, x, y, state):
"""
Mouse move callback
"""
lx = self._legalize_x(x)
if self.current_mouse_action == POSITION_DRAG:
self._set_clip_frame(lx)
self.parent_editor.clip_editor_frame_changed(self.current_clip_frame)
elif self.current_mouse_action == KF_DRAG:
if abs(lx - self.drag_start_x) < KF_DRAG_THRESHOLD:
return
frame = self._get_drag_frame(lx)
self.set_active_kf_frame(frame)
self.current_clip_frame = frame
self.parent_editor.keyframe_dragged(self.active_kf_index, frame)
self.parent_editor.active_keyframe_changed()
self.widget.queue_draw()
def _release_event(self, event):
"""
Mouse release callback.
"""
lx = self._legalize_x(event.x)
if self.current_mouse_action == POSITION_DRAG:
self._set_clip_frame(lx)
self.parent_editor.clip_editor_frame_changed(self.current_clip_frame)
self.parent_editor.update_slider_value_display(self.current_clip_frame)
elif self.current_mouse_action == KF_DRAG:
if abs(lx - self.drag_start_x) < KF_DRAG_THRESHOLD:
return
frame = self._get_drag_frame(lx)
self.set_active_kf_frame(frame)
self.current_clip_frame = frame
self.parent_editor.keyframe_dragged(self.active_kf_index, frame)
self.parent_editor.active_keyframe_changed()
self.parent_editor.update_property_value()
self.parent_editor.update_slider_value_display(frame)
self.widget.queue_draw()
self.current_mouse_action = None
self.drag_on = False
def _legalize_x(self, x):
"""
Get x in pixel range between end pads.
"""
w = self.widget.allocation.width
if x < END_PAD:
return END_PAD
elif x > w - END_PAD:
return w - END_PAD
else:
return x
def _force_current_in_frame_range(self):
if self.current_clip_frame < self.clip_in:
self.current_clip_frame = self.clip_in
if self.current_clip_frame > self.clip_in + self.clip_length:
self.current_clip_frame = self.clip_in + self.clip_length
def _get_drag_frame(self, panel_x):
"""
Get x in range available for current drag.
"""
frame = self._get_frame_for_panel_pos(panel_x)
if frame < self.drag_min:
frame = self.drag_min
if frame > self.drag_max:
frame = self.drag_max
return frame
def _key_frame_hit(self, x, y):
for i in range(0, len(self.keyframes)):
frame, val = self.keyframes[i]
frame_x = self._get_panel_pos_for_frame(frame)
frame_y = KF_Y + 6
if((abs(x - frame_x) < KF_HIT_WIDTH)
and (abs(y - frame_y) < KF_HIT_WIDTH)):
return i
return None
def add_keyframe(self, frame):
kf_index_on_frame = self.frame_has_keyframe(frame)
if kf_index_on_frame != -1:
# Trying add on top of existing keyframe makes it active
self.active_kf_index = kf_index_on_frame
return
for i in range(0, len(self.keyframes)):
kf_frame, kf_value = self.keyframes[i]
if kf_frame > frame:
prev_frame, prev_value = self.keyframes[i - 1]
self.keyframes.insert(i, (frame, prev_value))
self.active_kf_index = i
return
prev_frame, prev_value = self.keyframes[len(self.keyframes) - 1]
self.keyframes.append((frame, prev_value))
self.active_kf_index = len(self.keyframes) - 1
def print_keyframes(self):
print "clip edit keyframes:"
for i in range(0, len(self.keyframes)):
print self.keyframes[i]
def delete_active_keyframe(self):
if self.active_kf_index == 0:
# keyframe frame 0 cannot be removed
return
self.keyframes.pop(self.active_kf_index)
self.active_kf_index -= 1
if self.active_kf_index < 0:
self.active_kf_index = 0
self._set_pos_to_active_kf()
def set_next_active(self):
"""
Activates next keyframe or keeps last active to stay in range.
"""
self.active_kf_index += 1
if self.active_kf_index > (len(self.keyframes) - 1):
self.active_kf_index = len(self.keyframes) - 1
self._set_pos_to_active_kf()
def set_prev_active(self):
"""
Activates previous keyframe or keeps first active to stay in range.
"""
self.active_kf_index -= 1
if self.active_kf_index < 0:
self.active_kf_index = 0
self._set_pos_to_active_kf()
def _set_pos_to_active_kf(self):
frame, value = self.keyframes[self.active_kf_index]
self.current_clip_frame = frame
self._force_current_in_frame_range()
self.parent_editor.update_slider_value_display(self.current_clip_frame)
def frame_has_keyframe(self, frame):
"""
Returns index of keyframe if frame has keyframe or -1 if it doesn't.
"""
for i in range(0, len(self.keyframes)):
kf_frame, kf_value = self.keyframes[i]
if frame == kf_frame:
return i
return -1
def get_active_kf_frame(self):
frame, val = self.keyframes[self.active_kf_index]
return frame
def get_active_kf_value(self):
frame, val = self.keyframes[self.active_kf_index]
return val
def set_active_kf_value(self, new_value):
frame, val = self.keyframes.pop(self.active_kf_index)
self.keyframes.insert(self.active_kf_index,(frame, new_value))
def active_kf_pos_entered(self, frame):
if self.active_kf_index == 0:
return
prev_frame, val = self.keyframes[self.active_kf_index - 1]
prev_frame += 1
try:
next_frame, val = self.keyframes[self.active_kf_index + 1]
next_frame -= 1
except:
next_frame = self.clip_length - 1
frame = max(frame, prev_frame)
frame = min(frame, next_frame)
self.set_active_kf_frame(frame)
self.current_clip_frame = frame
def set_active_kf_frame(self, new_frame):
frame, val = self.keyframes.pop(self.active_kf_index)
self.keyframes.insert(self.active_kf_index,(new_frame, val))
# -------------------------------------------------------------- shape objects
class EditRect:
"""
Line box with corner and middle handles that user can use to set
position, width and height of rectangle geometry.
"""
def __init__(self, x, y, w, h):
self.edit_points = {}
self.x = x
self.y = y
self.w = w
self.h = h
self.start_x = None
self.start_y = None
self.start_w = None
self.start_h = None
self.start_op_x = None
self.start_op_y = None
self.projection_point = None
self.set_edit_points()
def set_geom(self, x, y, w, h):
self.x = x
self.y = y
self.w = w
self.h = h
self.set_edit_points()
def set_edit_points(self):
self.edit_points[TOP_LEFT] = (self.x, self.y)
self.edit_points[TOP_MIDDLE] = (self.x + self.w/2, self.y)
self.edit_points[TOP_RIGHT] = (self.x + self.w, self.y)
self.edit_points[MIDDLE_LEFT] = (self.x, self.y + self.h/2)
self.edit_points[MIDDLE_RIGHT] = (self.x + self.w, self.y + self.h/2)
self.edit_points[BOTTOM_LEFT] = (self.x, self.y + self.h)
self.edit_points[BOTTOM_MIDDLE] = (self.x + self.w/2, self.y + self.h)
self.edit_points[BOTTOM_RIGHT] = (self.x + self.w, self.y + self.h)
def check_hit(self, x, y):
for id_int, value in self.edit_points.iteritems():
x1, y1 = value
if (x >= x1 - EP_HALF and x <= x1 + EP_HALF and y >= y1 - EP_HALF and y <= y1 + EP_HALF):
return id_int
x1, y1 = self.edit_points[TOP_LEFT]
x2, y2 = self.edit_points[BOTTOM_RIGHT]
if (x >= x1 and x <= x2 and y >= y1 and y <= y2):
return AREA_HIT
return NO_HIT
def edit_point_drag_started(self, ep_id):
opposite_id = (ep_id + 4) % 8
self.drag_ep = ep_id
self.guide_line = viewgeom.get_line_for_points( self.edit_points[ep_id],
self.edit_points[opposite_id])
x, y = self.edit_points[ep_id]
self.start_x = x
self.start_y = y
opx, opy = self.edit_points[opposite_id]
self.start_op_x = opx
self.start_op_y = opy
self.start_w = self.w
self.start_h = self.h
self.projection_point = (x, y)
def edit_point_drag(self, delta_x, delta_y):
x = self.start_x + delta_x
y = self.start_y + delta_y
p = (x, y)
lx, ly = self.guide_line.get_normal_projection_point(p)
self.projection_point = (lx, ly)
# Set new rect
if self.drag_ep == TOP_LEFT:
self.x = lx
self.y = ly
self.w = self.start_op_x - lx
self.h = self.start_op_y - ly
elif self.drag_ep == BOTTOM_RIGHT:
self.x = self.start_op_x
self.y = self.start_op_y
self.w = lx - self.start_op_x
self.h = ly - self.start_op_y
elif self.drag_ep == BOTTOM_LEFT:
self.x = lx
self.y = self.start_op_y
self.w = self.start_op_x - lx
self.h = ly - self.start_op_y
elif self.drag_ep == TOP_RIGHT:
self.x = self.start_op_x
self.y = ly
self.w = lx - self.start_op_x
self.h = self.start_op_y - ly
elif self.drag_ep == MIDDLE_RIGHT:
self.x = self.start_op_x
self.y = self.start_op_y - (self.start_h / 2.0)
self.w = lx - self.start_op_x
self.h = self.start_h
elif self.drag_ep == MIDDLE_LEFT:
self.x = lx
self.y = self.start_y - (self.start_h / 2.0)
self.w = self.start_op_x - lx
self.h = self.start_h
elif self.drag_ep == TOP_MIDDLE:
self.x = self.start_x - (self.start_w / 2.0)
self.y = ly
self.w = self.start_w
self.h = self.start_op_y - ly
elif self.drag_ep == BOTTOM_MIDDLE:
self.x = self.start_op_x - (self.start_w / 2.0)
self.y = self.start_op_y
self.w = self.start_w
self.h = ly - self.start_op_y
# No negative size
if self.w < 1.0:
self.w = 1.0
if self.h < 1.0:
self.h = 1.0
self.set_edit_points()
def clear_projection_point(self):
self.projection_point = None
def move_started(self):
self.start_x = self.x
self.start_y = self.y
def move_drag(self, delta_x, delta_y):
self.x = self.start_x + delta_x
self.y = self.start_y + delta_y
self.set_edit_points()
def draw(self, cr):
# Box
cr.set_line_width(1.0)
color = EDITABLE_RECT_COLOR
cr.set_source_rgb(*color)
cr.rectangle(self.x + 0.5, self.y + 0.5, self.w, self.h)
cr.stroke()
# handles
for id_int, pos in self.edit_points.iteritems():
x, y = pos
cr.rectangle(x - 2, y - 2, 4, 4)
cr.fill()
if self.projection_point != None:
x, y = self.projection_point
cr.set_source_rgb(0,1,0)
cr.rectangle(x - 2, y - 2, 4, 4)
cr.fill()
# ---------------------------------------------------- screen editors
def _geom_kf_sort(kf):
"""
Function is used to sort keyframes by frame number.
"""
frame, shape, opacity = kf
return frame
class AbstractScreenEditor:
"""
Base class for editors used to edit something on top of rectangle representing
screen.
"""
def __init__(self, editable_property, parent_editor):
self.widget = CairoDrawableArea(GEOMETRY_EDITOR_WIDTH,
GEOMETRY_EDITOR_HEIGHT,
self._draw)
self.widget.press_func = self._press_event
self.widget.motion_notify_func = self._motion_notify_event
self.widget.release_func = self._release_event
self.clip_length = editable_property.get_clip_length()
self.pixel_aspect_ratio = editable_property.get_pixel_aspect_ratio()
self.current_clip_frame = 0
# Keyframe tuples are of type (frame, rect, opacity)
self.keyframes = None # Set using set_keyframes() keyframes are in form [frame, shape, opacity]
self.keyframe_parser = None # Function used to parse keyframes to tuples is different for different expressions
# Parent editor sets this.
self.current_mouse_hit = None
self.start_x = None
self.start_Y = None
self.parent_editor = parent_editor
self.source_width = -1 # unscaled source image width, set later
self.source_height = -1 # unscaled source image height, set later
self.coords = None # Calculated later when we have allocation available
def init_editor(self, source_width, source_height, y_fract):
self.source_width = source_width
self.source_height = source_height
self.y_fract = y_fract
self.screen_ratio = float(source_width) / float(source_height)
# ---------------------------------------------------- draw params
def _create_coords(self):
self.coords = utils.EmptyClass()
panel_w = self.widget.allocation.width
panel_h = self.widget.allocation.height
self.coords.screen_h = panel_h * self.y_fract
self.coords.screen_w = self.coords.screen_h * self.screen_ratio * self.pixel_aspect_ratio
self.coords.orig_x = (panel_w - self.coords.screen_w) / 2.0
self.coords.orig_y = (panel_h - self.coords.screen_h) / 2.0
self.coords.x_scale = self.source_width / self.coords.screen_w
self.coords.y_scale = self.source_height / self.coords.screen_h
def set_view_size(self, y_fract):
self.y_fract = y_fract
self._create_coords()
def get_screen_x(self, x):
p_x_from_origo = x - self.coords.orig_x
return p_x_from_origo * self.coords.x_scale
def get_screen_y(self, y):
p_y_from_origo = y - self.coords.orig_y
return p_y_from_origo * self.coords.y_scale
def get_panel_point(self, x, y):
px = self.coords.orig_x + x / self.coords.x_scale
py = self.coords.orig_y + y / self.coords.y_scale
return (px, py)
# --------------------------------------------------------- updates
def set_clip_frame(self, frame):
self.current_clip_frame = frame
self._clip_frame_changed()
def _clip_frame_changed(self):
print "_clip_frame_changed not impl"
def set_keyframe_to_edit_shape(self, kf_index):
value_shape = self._get_current_screen_shape()
frame, shape, opacity = self.keyframes[kf_index]
self.keyframes.pop(kf_index)
new_kf = (frame, value_shape, opacity)
self.keyframes.append(new_kf)
self.keyframes.sort(key=_geom_kf_sort)
self._update_shape()
def _get_current_screen_shape(self):
print "_get_current_screen_shape not impl"
def _update_shape(self):
print "_update_shape not impl"
# ------------------------------------------------- keyframes
def add_keyframe(self, frame):
if self._frame_has_keyframe(frame) == True:
return
# Get previous keyframe
prev_kf = None
for i in range(0, len(self.keyframes)):
p_frame, p_shape, p_opacity = self.keyframes[i]
if p_frame < frame:
prev_kf = self.keyframes[i]
if prev_kf == None:
prev_kf = self.keyframes[len(self.keyframes) - 1]
# Add with values of previous
p_frame, p_shape, p_opacity = prev_kf
self.keyframes.append((frame, copy.deepcopy(p_shape), copy.deepcopy(p_opacity)))
self.keyframes.sort(key=_geom_kf_sort)
def delete_active_keyframe(self, keyframe_index):
#print keyframe_index
if keyframe_index == 0:
# keyframe frame 0 cannot be removed
return
self.keyframes.pop(keyframe_index)
def _frame_has_keyframe(self, frame):
for i in range(0, len(self.keyframes)):
kf = self.keyframes[i]
kf_frame, rect, opacity = kf
if frame == kf_frame:
return True
return False
def set_keyframes(self, keyframes_str, out_to_in_func):
self.keyframes = self.keyframe_parser(keyframes_str, out_to_in_func)
def set_keyframe_frame(self, active_kf_index, frame):
old_frame, shape, opacity = self.keyframes[active_kf_index]
self.keyframes.pop(active_kf_index)
self.keyframes.insert(active_kf_index, (frame, shape, opacity))
# ---------------------------------------------------- editor menu actions
def reset_active_keyframe_shape(self, active_kf_index):
print "reset_active_keyframe_shape not impl"
def reset_active_keyframe_rect_shape(self, active_kf_index):
print "reset_active_keyframe_rect_shape not impl"
def center_h_active_keyframe_shape(self, active_kf_index):
print "center_h_active_keyframe_shape not impl"
def center_v_active_keyframe_shape(self, active_kf_index):
print "center_v_active_keyframe_shape not impl"
# ------------------------------------------------------ arrow edit
def handle_arrow_edit(self, keyval):
print "handle_arrow_edit not impl"
# -------------------------------------------------------- mouse events
def _press_event(self, event):
"""
Mouse button callback
"""
self.current_mouse_hit = self._check_shape_hit(event.x, event.y)
if self.current_mouse_hit == NO_HIT:
return
self.mouse_start_x = event.x
self.mouse_start_y = event.y
self._shape_press_event()
self.parent_editor.geometry_edit_started()
self.parent_editor.update_request_from_geom_editor()
def _check_shape_hit(self, x, y):
print "_check_shape_hit not impl"
def _shape_press_event(self):
print "_shape_press_event not impl"
def _motion_notify_event(self, x, y, state):
"""
Mouse move callback
"""
if self.current_mouse_hit == NO_HIT:
return
delta_x = x - self.mouse_start_x
delta_y = y - self.mouse_start_y
self._shape__motion_notify_event(delta_x, delta_y)
self.parent_editor.queue_draw()
def _shape__motion_notify_event(self, delta_x, delta_y):
print "_shape__motion_notify_event not impl"
def _release_event(self, event):
if self.current_mouse_hit == NO_HIT:
return
delta_x = event.x - self.mouse_start_x
delta_y = event.y - self.mouse_start_y
self._shape_release_event(delta_x, delta_y)
self.parent_editor.geometry_edit_finished()
def _shape_release_event(self, delta_x, delta_y):
print "_shape_release_event not impl"
# ----------------------------------------------- drawing
def _draw(self, event, cr, allocation):
"""
Callback for repaint from CairoDrawableArea.
We get cairo contect and allocation.
"""
if self.coords == None:
self._create_coords()
x, y, w, h = allocation
# Draw bg
cr.set_source_rgb(*(gui.bg_color_tuple))
cr.rectangle(0, 0, w, h)
cr.fill()
# Draw screen
cr.set_source_rgb(0.6, 0.6, 0.6)
cr.rectangle(self.coords.orig_x, self.coords.orig_y,
self.coords.screen_w, self.coords.screen_h)
cr.fill()
screen_rect = [self.coords.orig_x, self.coords.orig_y,
self.coords.screen_w, self.coords.screen_h]
self._draw_edge(cr, screen_rect)
self._draw_edit_shape(cr, allocation)
def _draw_edge(self, cr, rect):
cr.set_line_width(1.0)
cr.set_source_rgb(0, 0, 0)
cr.rectangle(rect[0] + 0.5, rect[1] + 0.5, rect[2], rect[3])
cr.stroke()
def _draw_edit_shape(self, cr, allocation):
print "_draw_edit_shape not impl."
class BoxGeometryScreenEditor(AbstractScreenEditor):
"""
GUI component for editing position and scale values of keyframes
of source image in compositors.
Component is used as a part of e.g GeometryEditor, which handles
also keyframe creation and deletion and opacity, and
writing out the keyframes with combined information.
Needed parent_editor callback interface:
def geometry_edit_started(self)
def geometry_edit_finished(self)
def update_request_from_geom_editor(self)
"""
def __init__(self, editable_property, parent_editor):
AbstractScreenEditor.__init__(self, editable_property, parent_editor)
self.source_edit_rect = None # Created later when we have allocation available
def reset_active_keyframe_shape(self, active_kf_index):
frame, old_rect, opacity = self.keyframes[active_kf_index]
rect = [0, 0, self.source_width, self.source_height]
self.keyframes.pop(active_kf_index)
self.keyframes.insert(active_kf_index, (frame, rect, opacity))
def reset_active_keyframe_rect_shape(self, active_kf_index):
frame, old_rect, opacity = self.keyframes[active_kf_index]
x, y, w, h = old_rect
new_h = int(float(w) * (float(self.source_height) / float(self.source_width)))
rect = [x, y, w, new_h]
self.keyframes.pop(active_kf_index)
self.keyframes.insert(active_kf_index, (frame, rect, opacity))
def center_h_active_keyframe_shape(self, active_kf_index):
frame, old_rect, opacity = self.keyframes[active_kf_index]
ox, y, w, h = old_rect
x = self.source_width / 2 - w / 2
rect = [x, y, w, h ]
self.keyframes.pop(active_kf_index)
self.keyframes.insert(active_kf_index, (frame, rect, opacity))
def center_v_active_keyframe_shape(self, active_kf_index):
frame, old_rect, opacity = self.keyframes[active_kf_index]
x, oy, w, h = old_rect
y = self.source_height / 2 - h / 2
rect = [x, y, w, h ]
self.keyframes.pop(active_kf_index)
self.keyframes.insert(active_kf_index, (frame, rect, opacity))
def _clip_frame_changed(self):
if self.source_edit_rect != None:
self._update_source_rect()
def _update_shape(self):
self._update_source_rect()
def _update_source_rect(self):
for i in range(0, len(self.keyframes)):
frame, rect, opacity = self.keyframes[i]
if frame == self.current_clip_frame:
self.source_edit_rect.set_geom(*self._get_screen_to_panel_rect(rect))
#self.source_edit_rect.editable = True
return
try:
# See if frame between this and next keyframe
frame_n, rect_n, opacity_n = self.keyframes[i + 1]
if ((frame < self.current_clip_frame)
and (self.current_clip_frame < frame_n)):
time_fract = float((self.current_clip_frame - frame)) / \
float((frame_n - frame))
frame_rect = self._get_interpolated_rect(rect, rect_n, time_fract)
self.source_edit_rect.set_geom(*self._get_screen_to_panel_rect(frame_rect))
#self.source_edit_rect.editable = False
return
except: # past last frame, use its value
self.source_edit_rect.set_geom(*self._get_screen_to_panel_rect(rect))
#self.source_edit_rect.editable = False
return
print "reached end of _update_source_rect, this should be unreachable"
def _get_interpolated_rect(self, rect_1, rect_2, fract):
x1, y1, w1, h1 = rect_1
x2, y2, w2, h2 = rect_2
x = x1 + (x2 - x1) * fract
y = y1 + (y2 - y1) * fract
w = w1 + (w2 - w1) * fract
h = h1 + (h2 - h1) * fract
return (x, y, w, h)
def _get_screen_to_panel_rect(self, rect):
x, y, w, h = rect
px = self.coords.orig_x + x / self.coords.x_scale
py = self.coords.orig_y + y / self.coords.y_scale
pw = w / self.coords.x_scale # scale is panel to screen, this is screen to panel
ph = h / self.coords.y_scale # scale is panel to screen, this is screen to panel
return (px, py, pw, ph)
def _get_current_screen_shape(self):
return self._get_source_edit_rect_to_screen_rect()
def _get_source_edit_rect_to_screen_rect(self):
p_x_from_origo = self.source_edit_rect.x - self.coords.orig_x
p_y_from_origo = self.source_edit_rect.y - self.coords.orig_y
screen_x = p_x_from_origo * self.coords.x_scale
screen_y = p_y_from_origo * self.coords.y_scale
screen_w = self.source_edit_rect.w * self.coords.x_scale
screen_h = self.source_edit_rect.h * self.coords.y_scale
return [screen_x, screen_y, screen_w, screen_h]
def _draw_edit_shape(self, cr, allocation):
# Edit rect is created here only when we're sure to have allocation
if self.source_edit_rect == None:
self.source_edit_rect = EditRect(10, 10, 10, 10) # values are immediatyly overwritten
self._update_source_rect()
# Draw source
self.source_edit_rect.draw(cr)
# ----------------------------------------- mouse press event
def _check_shape_hit(self, x, y):
return self.source_edit_rect.check_hit(x, y)
def _shape_press_event(self):
if self.current_mouse_hit == AREA_HIT:
self.source_edit_rect.move_started()
else:
self.source_edit_rect.edit_point_drag_started(self.current_mouse_hit)
def _shape__motion_notify_event(self, delta_x, delta_y):
if self.current_mouse_hit == AREA_HIT:
self.source_edit_rect.move_drag(delta_x, delta_y)
else:
self.source_edit_rect.edit_point_drag(delta_x, delta_y)
def _shape_release_event(self, delta_x, delta_y):
if self.current_mouse_hit == AREA_HIT:
self.source_edit_rect.move_drag(delta_x, delta_y)
else:
self.source_edit_rect.edit_point_drag(delta_x, delta_y)
self.source_edit_rect.clear_projection_point()
def handle_arrow_edit(self, keyval):
if keyval == gtk.keysyms.Left:
self.source_edit_rect.x -= 1
if keyval == gtk.keysyms.Right:
self.source_edit_rect.x += 1
if keyval == gtk.keysyms.Up:
self.source_edit_rect.y -= 1
if keyval == gtk.keysyms.Down:
self.source_edit_rect.y += 1
def print_keyframes(self):
for i in range(0, len(self.keyframes)):
print self.keyframes[i]
class RotatingScreenEditor(AbstractScreenEditor):
"""
Needed parent_editor callback interface:
def geometry_edit_started(self)
def geometry_edit_finished(self)
def update_request_from_geom_editor(self)
Keyframes in form: [frame, [x, y, x_scale, y_scale, rotation] opacity]
"""
def __init__(self, editable_property, parent_editor):
AbstractScreenEditor.__init__(self, editable_property, parent_editor)
self.edit_points = []
self.shape_x = None
self.shape_y = None
self.rotation = None
self.x_scale = None
self.y_scale = None
def create_edit_points_and_values(self):
# creates untransformed edit shape to init array, values will overridden shortly
self.edit_points.append((self.source_width / 2, self.source_height / 2)) # center
self.edit_points.append((self.source_width, self.source_height / 2)) # x_Scale
self.edit_points.append((self.source_width / 2, 0)) # y_Scale
self.edit_points.append((0, 0)) # rotation
self.edit_points.append((self.source_width, 0)) # top right
self.edit_points.append((self.source_width, self.source_height)) # bottom right
self.edit_points.append((0, self.source_height)) # bottom left
self.untrans_points = copy.deepcopy(self.edit_points)
self.shape_x = self.source_width / 2 # always == self.edit_points[0] x
self.shape_y = self.source_height / 2 # always == self.edit_points[0] y
self.rotation = 0.0
self.x_scale = 1.0
self.y_scale = 1.0
# ------------------------------------------ hit testing
def _check_shape_hit(self, x, y):
edit_panel_points = []
for ep in self.edit_points:
edit_panel_points.append(self.get_panel_point(*ep))
for i in range(0, 4):
if self._check_point_hit((x, y), edit_panel_points[i], 10):
return i #indexes correspond to edit_point_handle indexes
if viewgeom.point_in_convex_polygon((x, y), edit_panel_points[3:7], 0) == True: # corners are edit points 3, 4, 5, 6
return AREA_HIT
return NO_HIT
def _check_point_hit(self, p, ep, TARGET_HALF):
x, y = p
ex, ey = ep
if (x >= ex - TARGET_HALF and x <= ex + TARGET_HALF and y >= ey - TARGET_HALF and y <= ey + TARGET_HALF):
return True
return False
# ------------------------------------------------------- menu edit events
def reset_active_keyframe_shape(self, active_kf_index):
frame, trans, opacity = self.keyframes[active_kf_index]
new_trans = [self.source_width / 2, self.source_height / 2, 1.0, 1.0, 0]
self.keyframes.pop(active_kf_index)
self.keyframes.insert(active_kf_index, (frame, new_trans, opacity))
self._update_shape()
def reset_active_keyframe_rect_shape(self, active_kf_index):
frame, trans, opacity = self.keyframes[active_kf_index]
x, y, x_scale, y_scale, rotation = trans
new_trans = [x, y, x_scale, x_scale, rotation]
self.keyframes.pop(active_kf_index)
self.keyframes.insert(active_kf_index, (frame, new_trans, opacity))
self._update_shape()
def center_h_active_keyframe_shape(self, active_kf_index):
frame, trans, opacity = self.keyframes[active_kf_index]
x, y, x_scale, y_scale, rotation = trans
new_trans = [self.source_width / 2, y, x_scale, y_scale, rotation]
self.keyframes.pop(active_kf_index)
self.keyframes.insert(active_kf_index, (frame, new_trans, opacity))
self._update_shape()
def center_v_active_keyframe_shape(self, active_kf_index):
frame, trans, opacity = self.keyframes[active_kf_index]
x, y, x_scale, y_scale, rotation = trans
new_trans = [x, self.source_height / 2, x_scale, y_scale, rotation]
self.keyframes.pop(active_kf_index)
self.keyframes.insert(active_kf_index, (frame, new_trans, opacity))
self._update_shape()
# -------------------------------------------------------- updating
def _clip_frame_changed(self):
self._update_shape()
def _get_current_screen_shape(self):
return [self.shape_x, self.shape_y, self.x_scale, self.y_scale, self.rotation]
def _update_shape(self):
for i in range(0, len(self.keyframes)):
frame, rect, opacity = self.keyframes[i]
if frame == self.current_clip_frame:
self.set_geom(*rect)
return
try:
# See if frame between this and next keyframe
frame_n, rect_n, opacity_n = self.keyframes[i + 1]
if ((frame < self.current_clip_frame)
and (self.current_clip_frame < frame_n)):
time_fract = float((self.current_clip_frame - frame)) / \
float((frame_n - frame))
frame_rect = self._get_interpolated_rect(rect, rect_n, time_fract)
self.set_geom(*frame_rect)
return
except: # past last frame, use its value ( line: frame_n, rect_n, opacity_n = self.keyframes[i + 1] failed)
self.set_geom(*rect)
return
def set_geom(self, x, y, x_scale, y_scale, rotation):
#print "set geom", x, y, x_scale, y_scale, rotation
self.shape_x = x
self.shape_y = y
self.x_scale = x_scale
self.y_scale = y_scale
self.rotation = rotation
self._update_edit_points()
def _get_interpolated_rect(self, rect_1, rect_2, fract):
x1, y1, xs1, ys1, r1 = rect_1
x2, y2, xs2, ys2, r2 = rect_2
x = x1 + (x2 - x1) * fract
y = y1 + (y2 - y1) * fract
xs = xs1 + (xs2 - xs1) * fract
ys = ys1 + (ys2 - ys1) * fract
r = r1 + (r2 - r1) * fract
return (x, y, xs, ys, r)
# --------------------------------------------------------- mouse events
def _shape_press_event(self):
self.start_edit_points = copy.deepcopy(self.edit_points)
if self.current_mouse_hit == X_SCALE_HANDLE:
self.guide = viewgeom.get_vec_for_points((self.shape_x,self.shape_y), self.edit_points[X_SCALE_HANDLE])
elif self.current_mouse_hit == Y_SCALE_HANDLE:
self.guide = viewgeom.get_vec_for_points((self.shape_x,self.shape_y), self.edit_points[Y_SCALE_HANDLE])
elif self.current_mouse_hit == ROTATION_HANDLE:
ax, ay = self.edit_points[POS_HANDLE]
zero_deg_point = (ax, ay + 10)
m_end_point = (self.get_screen_x(self.mouse_start_x), self.get_screen_y(self.mouse_start_y))
self.mouse_start_rotation = viewgeom.get_angle_in_deg(zero_deg_point, self.edit_points[POS_HANDLE], m_end_point)
self.mouse_rotation_last = 0.0
self.rotation_value_start = self.rotation
elif self.current_mouse_hit == POS_HANDLE or self.current_mouse_hit == AREA_HIT:
self.start_shape_x = self.shape_x
self.start_shape_y = self.shape_y
def _shape__motion_notify_event(self, delta_x, delta_y):
self._update_values_for_mouse_delta(delta_x, delta_y)
def _shape_release_event(self, delta_x, delta_y):
self._update_values_for_mouse_delta(delta_x, delta_y)
def _update_values_for_mouse_delta(self, delta_x, delta_y):
if self.current_mouse_hit == POS_HANDLE or self.current_mouse_hit == AREA_HIT:
dx = self.get_screen_x(self.coords.orig_x + delta_x)
dy = self.get_screen_y(self.coords.orig_y + delta_y)
self.shape_x = self.start_shape_x + dx
self.shape_y = self.start_shape_y + dy
self._update_edit_points()
elif self.current_mouse_hit == X_SCALE_HANDLE:
dp = self.get_delta_point(delta_x, delta_y, self.edit_points[X_SCALE_HANDLE])
pp = self.guide.get_normal_projection_point(dp)
dist = viewgeom.distance(self.edit_points[POS_HANDLE], pp)
orig_dist = viewgeom.distance(self.untrans_points[POS_HANDLE], self.untrans_points[X_SCALE_HANDLE])
self.x_scale = dist / orig_dist
self._update_edit_points()
elif self.current_mouse_hit == Y_SCALE_HANDLE:
dp = self.get_delta_point(delta_x, delta_y, self.edit_points[Y_SCALE_HANDLE])
pp = self.guide.get_normal_projection_point(dp)
dist = viewgeom.distance(self.edit_points[POS_HANDLE], pp)
orig_dist = viewgeom.distance(self.untrans_points[POS_HANDLE], self.untrans_points[Y_SCALE_HANDLE])
self.y_scale = dist / orig_dist
self._update_edit_points()
elif self.current_mouse_hit == ROTATION_HANDLE:
ax, ay = self.edit_points[POS_HANDLE]
m_start_point = (self.get_screen_x(self.mouse_start_x), self.get_screen_y(self.mouse_start_y))
m_end_point = (self.get_screen_x(self.mouse_start_x + delta_x), self.get_screen_y(self.mouse_start_y + delta_y))
current_mouse_rotation = self.get_mouse_rotation_angle(self.edit_points[POS_HANDLE], m_start_point, m_end_point)
self.rotation = self.rotation_value_start + current_mouse_rotation
self._update_edit_points()
def get_mouse_rotation_angle(self, anchor, mr_start, mr_end):
angle = viewgeom.get_angle_in_deg(mr_start, anchor, mr_end)
clockw = viewgeom.points_clockwise(mr_start, anchor, mr_end)
if not clockw:
angle = -angle
# Crossed angle for 180 -> 181... range
crossed_angle = angle + 360.0
# Crossed angle for -180 -> 181 ...range.
if angle > 0:
crossed_angle = -360.0 + angle
# See if crossed angle closer to last angle.
if abs(self.mouse_rotation_last - crossed_angle) < abs(self.mouse_rotation_last - angle):
angle = crossed_angle
# Set last to get good results next time.
self.mouse_rotation_last = angle
return angle
def get_delta_point(self, delta_x, delta_y, ep):
dx = self.get_screen_x(self.coords.orig_x + delta_x)
dy = self.get_screen_y(self.coords.orig_y + delta_y)
sx = self.get_screen_x(self.mouse_start_x)
sy = self.get_screen_y(self.mouse_start_y)
return (sx + dx, sy + dy)
def _update_edit_points(self):
self.edit_points = copy.deepcopy(self.untrans_points) #reset before transform
self._translate_edit_points()
self._scale_edit_points()
self._rotate_edit_points()
def _translate_edit_points(self):
ux, uy = self.untrans_points[0]
dx = self.shape_x - ux
dy = self.shape_y - uy
for i in range(0,len(self.edit_points)):
sx, sy = self.untrans_points[i]
self.edit_points[i] = (sx + dx, sy + dy)
def _scale_edit_points(self):
ax, ay = self.edit_points[0]
sax, say = self.untrans_points[0]
for i in range(1, 7):
sx, sy = self.untrans_points[i]
x = ax + self.x_scale * (sx - sax)
y = ay + self.y_scale * (sy - say)
self.edit_points[i] = (x, y)
def _rotate_edit_points(self):
ax, ay = self.edit_points[0]
for i in range(1, 7):
x, y = viewgeom.rotate_point_around_point(self.rotation, self.edit_points[i], self.edit_points[0])
self.edit_points[i] = (x, y)
def _draw_edit_shape(self, cr, allocation):
x, y = self.get_panel_point(*self.edit_points[3])
cr.move_to(x, y)
for i in range(4,7):
x, y = self.get_panel_point(*self.edit_points[i])
cr.line_to(x, y)
cr.close_path()
cr.stroke()
self._draw_scale_arrow(cr, self.edit_points[2], 90)
self._draw_scale_arrow(cr, self.edit_points[1], 0)
# center cross
x, y = self.get_panel_point(*self.edit_points[0])
cr.translate(x,y)
cr.rotate(math.radians(self.rotation))
CROSS_LENGTH = 3
cr.move_to(-0.5, -CROSS_LENGTH-0.5)
cr.line_to(-0.5, CROSS_LENGTH-0.5)
cr.set_line_width(1.0)
cr.stroke()
cr.move_to(-CROSS_LENGTH - 0.5, -0.5)
cr.line_to(CROSS_LENGTH - 0.5, -0.5)
cr.stroke()
cr.identity_matrix()
# roto handle
x, y = self.get_panel_point(*self.edit_points[3])
cr.translate(x,y)
cr.rotate(math.radians(self.rotation))
cr.arc(0, 0, 6, math.radians(180), math.radians(-35))
cr.set_line_width(3.0)
cr.stroke()
cr.move_to(-6, 3)
cr.line_to(-9, 0)
cr.line_to(-3, 0)
cr.close_path()
cr.fill()
cr.arc(0, 0, 6, math.radians(0), math.radians(145))
cr.set_line_width(3.0)
cr.stroke()
cr.move_to(6, -3)
cr.line_to(9, 0)
cr.line_to(3, 0)
cr.close_path()
cr.fill()
def _draw_scale_arrow(self, cr, edit_point, add_angle):
x, y = self.get_panel_point(*edit_point)
cr.translate(x,y)
cr.rotate(math.radians(self.rotation + add_angle))
SHAFT_WIDTH = 2
SHAFT_LENGTH = 6
HEAD_WIDTH = 6
HEAD_LENGTH = 6
cr.move_to(0, - SHAFT_WIDTH)
cr.line_to(SHAFT_LENGTH, -SHAFT_WIDTH)
cr.line_to(SHAFT_LENGTH, -HEAD_WIDTH)
cr.line_to(SHAFT_LENGTH + HEAD_LENGTH, 0)
cr.line_to(SHAFT_LENGTH, HEAD_WIDTH)
cr.line_to(SHAFT_LENGTH, SHAFT_WIDTH)
cr.line_to(-SHAFT_LENGTH, SHAFT_WIDTH)
cr.line_to(-SHAFT_LENGTH, HEAD_WIDTH)
cr.line_to(-SHAFT_LENGTH - HEAD_LENGTH, 0)
cr.line_to(-SHAFT_LENGTH, -HEAD_WIDTH)
cr.line_to(-SHAFT_LENGTH, -SHAFT_WIDTH)
cr.close_path()
cr.set_source_rgb(1,1,1)
cr.fill_preserve()
cr.set_line_width(2.0)
cr.set_source_rgb(0,0,0)
cr.stroke()
cr.identity_matrix()
# ----------------------------------------------------------- buttons objects
class ClipEditorButtonsRow(gtk.HBox):
"""
Row of buttons used to navigate and add keyframes and frame
entry box for active keyframe. Parent editor must implemnt interface
defined by connect methods:
editor_parent.add_pressed()
editor_parent.delete_pressed()
editor_parent.prev_pressed()
editor_parent.next_pressed()
editor_parent.prev_frame_pressed()
editor_parent.next_frame_pressed()
"""
def __init__(self, editor_parent):
gtk.HBox.__init__(self, False, 2)
# Buttons
self.add_button = guiutils.get_image_button("add_kf.png", BUTTON_WIDTH, BUTTON_HEIGHT)
self.delete_button = guiutils.get_image_button("delete_kf.png", BUTTON_WIDTH, BUTTON_HEIGHT)
self.prev_kf_button = guiutils.get_image_button("prev_kf.png", BUTTON_WIDTH, BUTTON_HEIGHT)
self.next_kf_button = guiutils.get_image_button("next_kf.png", BUTTON_WIDTH, BUTTON_HEIGHT)
self.prev_frame_button = guiutils.get_image_button("kf_edit_prev_frame.png", BUTTON_WIDTH, BUTTON_HEIGHT)
self.next_frame_button = guiutils.get_image_button("kf_edit_next_frame.png", BUTTON_WIDTH, BUTTON_HEIGHT)
self.add_button.connect("clicked", lambda w,e: editor_parent.add_pressed(), None)
self.delete_button.connect("clicked", lambda w,e: editor_parent.delete_pressed(), None)
self.prev_kf_button.connect("clicked", lambda w,e: editor_parent.prev_pressed(), None)
self.next_kf_button.connect("clicked", lambda w,e: editor_parent.next_pressed(), None)
self.prev_frame_button.connect("clicked", lambda w,e: editor_parent.prev_frame_pressed(), None)
self.next_frame_button.connect("clicked", lambda w,e: editor_parent.next_frame_pressed(), None)
# Position entry
self.kf_pos_label = gtk.Label()
self.modify_font(pango.FontDescription("light 8"))
self.kf_pos_label.set_text("0")
# Build row
self.pack_start(self.add_button, False, False, 0)
self.pack_start(self.delete_button, False, False, 0)
self.pack_start(self.prev_kf_button, False, False, 0)
self.pack_start(self.next_kf_button, False, False, 0)
self.pack_start(self.prev_frame_button, False, False, 0)
self.pack_start(self.next_frame_button, False, False, 0)
self.pack_start(gtk.Label(), True, True, 0)
self.pack_start(self.kf_pos_label, False, False, 0)
self.pack_start(guiutils.get_pad_label(1, 10), False, False, 0)
def set_frame(self, frame):
frame_str = utils.get_tc_string(frame)
self.kf_pos_label.set_text(frame_str)
class GeometryEditorButtonsRow(gtk.HBox):
def __init__(self, editor_parent):
"""
editor_parent needs to implement interface:
-------------------------------------------
editor_parent.view_size_changed(widget_active_index)
editor_parent.menu_item_activated()
"""
gtk.HBox.__init__(self, False, 2)
self.editor_parent = editor_parent
name_label = gtk.Label(_("View:"))
pixbuf = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "geom_action.png")
action_menu_button = guicomponents.PressLaunch(self._show_actions_menu, pixbuf, 24, 22)
size_select = gtk.combo_box_new_text()
size_select.append_text(_("Large"))
size_select.append_text(_("Medium"))
size_select.append_text(_("Small"))
size_select.set_active(1)
size_select.set_size_request(120, 30)
font_desc = pango.FontDescription("normal 9")
size_select.child.modify_font(font_desc)
size_select.connect("changed", lambda w,e: editor_parent.view_size_changed(w.get_active()),
None)
# Build row
self.pack_start(guiutils.get_pad_label(2, 10), False, False, 0)
self.pack_start(name_label, False, False, 0)
self.pack_start(size_select, False, False, 0)
self.pack_start(gtk.Label(), True, True, 0)
self.pack_start(action_menu_button.widget, False, False, 0)
self.pack_start(guiutils.get_pad_label(2, 10), False, False, 0)
def _show_actions_menu(self, widget, event):
menu = gtk.Menu()
menu.add(self._get_menu_item(_("Reset Geometry"), self.editor_parent.menu_item_activated, "reset" ))
menu.add(self._get_menu_item(_("Geometry to Original Aspect Ratio"), self.editor_parent.menu_item_activated, "ratio" ))
menu.add(self._get_menu_item(_("Center Horizontal"), self.editor_parent.menu_item_activated, "hcenter" ))
menu.add(self._get_menu_item(_("Center Vertical"), self.editor_parent.menu_item_activated, "vcenter" ))
menu.popup(None, None, None, event.button, event.time)
def _get_menu_item(self, text, callback, data):
item = gtk.MenuItem(text)
item.connect("activate", callback, data)
item.show()
return item
# ------------------------------------------------------------ master editors
class AbstractKeyFrameEditor(gtk.VBox):
"""
Extending editor is parent editor for ClipKeyFrameEditor and is updated
from timeline posion changes.
Extending editor also has slider for setting keyframe values.
"""
def __init__(self, editable_property, use_clip_in=True):
# editable_property is KeyFrameProperty
gtk.VBox.__init__(self, False, 2)
self.editable_property = editable_property
self.clip_tline_pos = editable_property.get_clip_tline_pos()
self.clip_editor = ClipKeyFrameEditor(editable_property, self, use_clip_in)
# Some filters start keyframes from *MEDIA* frame 0
# Some filters or compositors start keyframes from *CLIP* frame 0
# Filters starting from *media* 0 need offset to clip start added to all values
self.use_clip_in = use_clip_in
if self.use_clip_in == True:
self.clip_in = editable_property.clip.clip_in
else:
self.clip_in = 0
# Value slider
row, slider = guiutils.get_slider_row(editable_property, self.slider_value_changed)
self.value_slider_row = row
self.slider = slider
def display_tline_frame(self, tline_frame):
# This is called after timeline current frame changed.
# If timeline pos changed because drag is happening _here_,
# updating once more is wrong
if self.clip_editor.drag_on == True:
return
# update clipeditor pos
clip_frame = tline_frame - self.clip_tline_pos + self.clip_in
self.clip_editor.set_and_display_clip_frame(clip_frame)
self.update_editor_view(False)
def update_clip_pos(self):
# This is called after position of clip has been edited.
# We'll need to update some values to get keyframes on correct positions again
self.editable_property.update_clip_index()
self.clip_tline_pos = self.editable_property.get_clip_tline_pos()
if self.use_clip_in == True:
self.clip_in = self.editable_property.clip.clip_in
else:
self.clip_in = 0
self.clip_editor.clip_in = self.editable_property.clip.clip_in
def update_slider_value_display(self, frame):
# This is called after frame changed or mouse release to update
# slider value without causing 'changed' signal to update keyframes.
if self.editable_property.value_changed_ID != DISCONNECTED_SIGNAL_HANDLER:
self.slider.get_adjustment().handler_block(self.editable_property.value_changed_ID)
new_value = _get_frame_value(frame, self.clip_editor.keyframes)
self.editable_property.adjustment.set_value(new_value)
if self.editable_property.value_changed_ID != DISCONNECTED_SIGNAL_HANDLER:
self.slider.get_adjustment().handler_unblock(self.editable_property.value_changed_ID)
def seek_tline_frame(self, clip_frame):
PLAYER().seek_frame(self.clip_tline_pos + clip_frame - self.clip_in)
def update_editor_view(self, seek_tline=True):
print "update_editor_view not implemented"
class KeyFrameEditor(AbstractKeyFrameEditor):
"""
Class combines named value slider with ClipKeyFrameEditor and
control buttons to create keyframe editor for a single keyframed
numerical value property.
"""
def __init__(self, editable_property, use_clip_in=True):
AbstractKeyFrameEditor.__init__(self, editable_property, use_clip_in)
# default parser
self.clip_editor.keyframe_parser = propertyparse.single_value_keyframes_string_to_kf_array
# parsers for other editable_property types
if isinstance(editable_property, propertyedit.OpacityInGeomKeyframeProperty):
self.clip_editor.keyframe_parser = propertyparse.geom_keyframes_value_string_to_opacity_kf_array
editable_property.value.strip('"')
self.clip_editor.set_keyframes(editable_property.value, editable_property.get_in_value)
self.buttons_row = ClipEditorButtonsRow(self)
self.pack_start(self.value_slider_row, False, False, 0)
self.pack_start(self.clip_editor.widget, False, False, 0)
self.pack_start(self.buttons_row, False, False, 0)
self.active_keyframe_changed() # to do update gui to current values
def slider_value_changed(self, adjustment):
value = adjustment.get_value()
# Add key frame if were not on active key frame
active_kf_frame = self.clip_editor.get_active_kf_frame()
current_frame = self.clip_editor.current_clip_frame
if current_frame != active_kf_frame:
self.clip_editor.add_keyframe(current_frame)
self.clip_editor.set_active_kf_value(value)
self.update_editor_view()
self.update_property_value()
else: # if on kf, just update value
self.clip_editor.set_active_kf_value(value)
self.update_property_value()
def active_keyframe_changed(self):
frame = self.clip_editor.current_clip_frame
keyframes = self.clip_editor.keyframes
value = _get_frame_value(frame, keyframes)
self.slider.set_value(value)
self.buttons_row.set_frame(frame)
self.seek_tline_frame(frame)
def clip_editor_frame_changed(self, clip_frame):
self.seek_tline_frame(clip_frame)
self.buttons_row.set_frame(clip_frame)
def add_pressed(self):
self.clip_editor.add_keyframe(self.clip_editor.current_clip_frame)
self.update_editor_view()
self.update_property_value()
def delete_pressed(self):
self.clip_editor.delete_active_keyframe()
self.update_editor_view()
self.update_property_value()
def next_pressed(self):
self.clip_editor.set_next_active()
self.update_editor_view()
def prev_pressed(self):
self.clip_editor.set_prev_active()
self.update_editor_view()
def prev_frame_pressed(self):
self.clip_editor.move_clip_frame(-1)
self.update_editor_view()
def next_frame_pressed(self):
self.clip_editor.move_clip_frame(1)
self.update_editor_view()
def pos_entry_enter_hit(self, entry):
val = entry.get_text() #error handl?
self.clip_editor.active_kf_pos_entered(int(val))
self.update_editor_view()
self.update_property_value()
def keyframe_dragged(self, active_kf, frame):
pass
def update_editor_view(self, seek_tline=True):
frame = self.clip_editor.current_clip_frame
keyframes = self.clip_editor.keyframes
value = _get_frame_value(frame, keyframes)
self.buttons_row.set_frame(frame)
if seek_tline == True:
self.seek_tline_frame(frame)
self.queue_draw()
def connect_to_update_on_release(self):
self.editable_property.adjustment.disconnect(self.editable_property.value_changed_ID)
self.editable_property.value_changed_ID = DISCONNECTED_SIGNAL_HANDLER
self.slider.connect("button-release-event", lambda w, e:self.slider_value_changed(w.get_adjustment()))
def update_property_value(self):
self.editable_property.write_out_keyframes(self.clip_editor.keyframes)
class GeometryEditor(AbstractKeyFrameEditor):
"""
GUI component that edits position, scale and opacity of a MLT property.
"""
def __init__(self, editable_property, use_clip_in=True):
AbstractKeyFrameEditor.__init__(self, editable_property, use_clip_in)
self.init_geom_gui(editable_property)
self.init_non_geom_gui()
def init_geom_gui(self, editable_property):
self.geom_kf_edit = BoxGeometryScreenEditor(editable_property, self)
self.geom_kf_edit.init_editor(current_sequence().profile.width(),
current_sequence().profile.height(),
GEOM_EDITOR_SIZE_MEDIUM)
editable_property.value.strip('"')
self.geom_kf_edit.keyframe_parser = propertyparse.geom_keyframes_value_string_to_geom_kf_array
self.geom_kf_edit.set_keyframes(editable_property.value, editable_property.get_in_value)
def init_non_geom_gui(self):
# Create components
self.geom_buttons_row = GeometryEditorButtonsRow(self)
g_frame = gtk.Frame()
g_frame.set_shadow_type(gtk.SHADOW_ETCHED_IN)
g_frame.add(self.geom_kf_edit.widget)
self.buttons_row = ClipEditorButtonsRow(self)
# Create clip editor keyframes from geom editor keyframes
# that contain the property values when opening editor.
# From now on clip editor opacity values are used until editor is discarded.
keyframes = []
for kf in self.geom_kf_edit.keyframes:
frame, rect, opacity = kf
clip_kf = (frame, opacity)
keyframes.append(clip_kf)
self.clip_editor.keyframes = keyframes
# Build gui
self.pack_start(self.geom_buttons_row, False, False, 0)
self.pack_start(g_frame, False, False, 0)
self.pack_start(self.value_slider_row, False, False, 0)
self.pack_start(self.clip_editor.widget, False, False, 0)
self.pack_start(self.buttons_row, False, False, 0)
self.active_keyframe_changed() # to do update gui to current values
self.queue_draw()
def add_pressed(self):
self.clip_editor.add_keyframe(self.clip_editor.current_clip_frame)
self.geom_kf_edit.add_keyframe(self.clip_editor.current_clip_frame)
frame = self.clip_editor.get_active_kf_frame()
self.update_editor_view_with_frame(frame)
self.update_property_value()
def delete_pressed(self):
active = self.clip_editor.active_kf_index
self.clip_editor.delete_active_keyframe()
self.geom_kf_edit.delete_active_keyframe(active)
frame = self.clip_editor.get_active_kf_frame()
self.update_editor_view_with_frame(frame)
self.update_property_value()
def next_pressed(self):
self.clip_editor.set_next_active()
frame = self.clip_editor.get_active_kf_frame()
self.update_editor_view_with_frame(frame)
def prev_pressed(self):
self.clip_editor.set_prev_active()
frame = self.clip_editor.get_active_kf_frame()
self.update_editor_view_with_frame(frame)
def slider_value_changed(self, adjustment):
value = adjustment.get_value()
self.clip_editor.set_active_kf_value(value)
self.update_property_value()
def view_size_changed(self, selected_index):
y_fract = GEOM_EDITOR_SIZES[selected_index]
self.geom_kf_edit.set_view_size(y_fract)
self.update_editor_view_with_frame(self.clip_editor.current_clip_frame)
def clip_editor_frame_changed(self, frame):
self.update_editor_view_with_frame(frame)
def prev_frame_pressed(self):
self.clip_editor.move_clip_frame(-1)
self.update_editor_view(True)
def next_frame_pressed(self):
self.clip_editor.move_clip_frame(1)
self.update_editor_view(True)
def geometry_edit_started(self): # callback from geom_kf_edit
self.clip_editor.add_keyframe(self.clip_editor.current_clip_frame)
self.geom_kf_edit.add_keyframe(self.clip_editor.current_clip_frame)
def geometry_edit_finished(self): # callback from geom_kf_edit
self.geom_kf_edit.set_keyframe_to_edit_shape(self.clip_editor.active_kf_index)
self.update_editor_view_with_frame(self.clip_editor.current_clip_frame)
self.update_property_value()
def arrow_edit(self, keyval):
self.geom_kf_edit.handle_arrow_edit(keyval)
self.geom_kf_edit.set_keyframe_to_edit_shape(self.clip_editor.active_kf_index)
self.update_editor_view_with_frame(self.clip_editor.current_clip_frame)
self.update_property_value()
def update_request_from_geom_editor(self): # callback from geom_kf_edit
self.update_editor_view_with_frame(self.clip_editor.current_clip_frame)
def keyframe_dragged(self, active_kf, frame):
self.geom_kf_edit.set_keyframe_frame(active_kf, frame)
def active_keyframe_changed(self): # callback from clip_editor
kf_frame = self.clip_editor.get_active_kf_frame()
self.update_editor_view_with_frame(kf_frame)
def _reset_rect_pressed(self):
self.geom_kf_edit.reset_active_keyframe_shape(self.clip_editor.active_kf_index)
frame = self.clip_editor.get_active_kf_frame()
self.update_editor_view_with_frame(frame)
self.update_property_value()
def _reset_rect_ratio_pressed(self):
self.geom_kf_edit.reset_active_keyframe_rect_shape(self.clip_editor.active_kf_index)
frame = self.clip_editor.get_active_kf_frame()
self.update_editor_view_with_frame(frame)
self.update_property_value()
def _center_horizontal(self):
self.geom_kf_edit.center_h_active_keyframe_shape(self.clip_editor.active_kf_index)
frame = self.clip_editor.get_active_kf_frame()
self.update_editor_view_with_frame(frame)
self.update_property_value()
def _center_vertical(self):
self.geom_kf_edit.center_v_active_keyframe_shape(self.clip_editor.active_kf_index)
frame = self.clip_editor.get_active_kf_frame()
self.update_editor_view_with_frame(frame)
self.update_property_value()
def menu_item_activated(self, widget, data):
if data == "reset":
self._reset_rect_pressed()
elif data == "ratio":
self._reset_rect_ratio_pressed()
elif data == "hcenter":
self._center_horizontal()
elif data == "vcenter":
self._center_vertical()
def update_editor_view(self, seek_tline_frame=False):
# This gets called when tline frame is changed from outside
# Call update_editor_view_with_frame that is used when udating from inside the object.
# seek_tline_frame will be False to stop endless loop of updates
frame = self.clip_editor.current_clip_frame
self.update_editor_view_with_frame(frame, seek_tline_frame)
def update_editor_view_with_frame(self, frame, seek_tline_frame=True):
self.update_slider_value_display(frame)
self.geom_kf_edit.set_clip_frame(frame)
self.buttons_row.set_frame(frame)
if seek_tline_frame == True:
self.seek_tline_frame(frame)
self.queue_draw()
def seek_tline_frame(self, clip_frame):
PLAYER().seek_frame(self.clip_tline_pos + clip_frame)
def update_property_value(self):
write_keyframes = []
for opa_kf, geom_kf in zip(self.clip_editor.keyframes, self.geom_kf_edit.keyframes):
frame, opacity = opa_kf
frame, rect, rubbish_opacity = geom_kf # rubbish_opacity was just doing same thing twice for nothing,
# and can be removed to clean up code, but could not bothered right now
write_keyframes.append((frame, rect, opacity))
self.editable_property.write_out_keyframes(write_keyframes)
class RotatingGeometryEditor(GeometryEditor):
def init_geom_gui(self, editable_property):
self.geom_kf_edit = RotatingScreenEditor(editable_property, self)
self.geom_kf_edit.init_editor(current_sequence().profile.width(),
current_sequence().profile.height(),
GEOM_EDITOR_SIZE_MEDIUM)
self.geom_kf_edit.create_edit_points_and_values()
editable_property.value.strip('"')
self.geom_kf_edit.keyframe_parser = propertyparse.rotating_geom_keyframes_value_string_to_geom_kf_array
self.geom_kf_edit.set_keyframes(editable_property.value, editable_property.get_in_value)
def rotating_ge_write_out_keyframes(ep, keyframes):
x_val = ""
y_val = ""
x_scale_val = ""
y_scale_val = ""
rotation_val = ""
opacity_val = ""
for kf in keyframes:
frame, transf, opacity = kf
x, y, x_scale, y_scale, rotation = transf
x_val += str(frame) + "=" + str(propertyparse.get_frei0r_cairo_position(x, ep.profile_width)) + ";"
y_val += str(frame) + "=" + str(propertyparse.get_frei0r_cairo_position(y, ep.profile_height)) + ";"
x_scale_val += str(frame) + "=" + str(propertyparse.get_frei0r_cairo_scale(x_scale)) + ";"
y_scale_val += str(frame) + "=" + str(propertyparse.get_frei0r_cairo_scale(y_scale)) + ";"
rotation_val += str(frame) + "=" + str(rotation / 360.0) + ";"
opacity_val += str(frame) + "=" + str(opacity / 100.0) + ";"
x_val = x_val.strip(";")
y_val = y_val.strip(";")
x_scale_val = x_scale_val.strip(";")
y_scale_val = y_scale_val.strip(";")
rotation_val = rotation_val.strip(";")
opacity_val = opacity_val.strip(";")
ep.x.write_value(x_val)
ep.y.write_value(y_val)
ep.x_scale.write_value(x_scale_val)
ep.y_scale.write_value(y_scale_val)
ep.rotation.write_value(rotation_val)
ep.opacity.write_value(opacity_val)
# ----------------------------------------------------------------- linear interpolation
def _get_frame_value(frame, keyframes):
for i in range(0, len(keyframes)):
kf_frame, kf_value = keyframes[i]
if kf_frame == frame:
return kf_value
try:
# See if frame between this and next keyframe
frame_n, value_n = keyframes[i + 1]
if ((kf_frame < frame)
and (frame < frame_n)):
time_fract = float((frame - kf_frame)) / float((frame_n - kf_frame))
value_range = value_n - kf_value
return kf_value + time_fract * value_range
except: # past last frame, use its value
return kf_value
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2014 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
"""
import pygtk
pygtk.require('2.0');
import gtk
import audiomonitoring
import editevent
import editorpersistance
import editorstate
import glassbuttons
import gui
import guicomponents
import guiutils
import respaths
import titler
import tlineaction
import updater
import undo
# editor window object
# This needs to be set here because gui.py module ref is not available at init time
w = None
m_pixbufs = None
MIDDLE_ROW_HEIGHT = 30 # height of middle row gets set here
BUTTON_HEIGHT = 28 # middle edit buttons row
BUTTON_WIDTH = 48 # middle edit buttons row
def _show_buttons_TC_LEFT_layout(widget):
global w
w = gui.editor_window
if w == None:
return
if widget.get_active() == False:
return
_clear_container(w.edit_buttons_row)
_create_buttons(w)
fill_with_TC_LEFT_pattern(w.edit_buttons_row, w)
w.window.show_all()
editorpersistance.prefs.midbar_tc_left = True
editorpersistance.save()
def _show_buttons_TC_MIDDLE_layout(widget):
global w
w = gui.editor_window
if w == None:
return
if widget.get_active() == False:
return
_clear_container(w.edit_buttons_row)
_create_buttons(w)
fill_with_TC_MIDDLE_pattern(w.edit_buttons_row, w)
w.window.show_all()
editorpersistance.prefs.midbar_tc_left = False
editorpersistance.save()
def _show_monitor_info_toggled(widget):
editorpersistance.prefs.show_sequence_profile = widget.get_active()
editorpersistance.save()
if editorstate.timeline_visible():
name = editorstate.current_sequence().name
profile_desc = editorstate.current_sequence().profile.description()
if editorpersistance.prefs.show_sequence_profile:
gui.editor_window.monitor_source.set_text(name + " / " + profile_desc)
else:
gui.editor_window.monitor_source.set_text(name)
def create_edit_buttons_row_buttons(editor_window, modes_pixbufs):
global m_pixbufs
m_pixbufs = modes_pixbufs
_create_buttons(editor_window)
def _create_buttons(editor_window):
IMG_PATH = respaths.IMAGE_PATH
editor_window.big_TC = guicomponents.BigTCDisplay()
editor_window.modes_selector = guicomponents.ToolSelector(editor_window.mode_selector_pressed, m_pixbufs, 40, 22)
editor_window.zoom_buttons = glassbuttons.GlassButtonsGroup(46, 23, 2, 4, 5)
editor_window.zoom_buttons.add_button(gtk.gdk.pixbuf_new_from_file(IMG_PATH + "zoom_in.png"), updater.zoom_in)
editor_window.zoom_buttons.add_button(gtk.gdk.pixbuf_new_from_file(IMG_PATH + "zoom_out.png"), updater.zoom_out)
editor_window.zoom_buttons.add_button(gtk.gdk.pixbuf_new_from_file(IMG_PATH + "zoom_length.png"), updater.zoom_project_length)
editor_window.zoom_buttons.widget.set_tooltip_text(_("Zoom In - Mouse Middle Scroll\n Zoom Out - Mouse Middle Scroll\n Zoom Length - Mouse Middle Click"))
editor_window.edit_buttons = glassbuttons.GlassButtonsGroup(46, 23, 2, 4, 5)
editor_window.edit_buttons.add_button(gtk.gdk.pixbuf_new_from_file(IMG_PATH + "cut.png"), tlineaction.cut_pressed)
editor_window.edit_buttons.add_button(gtk.gdk.pixbuf_new_from_file(IMG_PATH + "splice_out.png"), tlineaction.splice_out_button_pressed)
editor_window.edit_buttons.add_button(gtk.gdk.pixbuf_new_from_file(IMG_PATH + "lift.png"), tlineaction.lift_button_pressed)
editor_window.edit_buttons.add_button(gtk.gdk.pixbuf_new_from_file(IMG_PATH + "resync.png"), tlineaction.resync_button_pressed)
editor_window.edit_buttons.widget.set_tooltip_text(_("Cut - X\nSplice Out - Delete\nLift\nResync Selected"))
editor_window.monitor_insert_buttons = glassbuttons.GlassButtonsGroup(46, 23, 2, 4, 5)
editor_window.monitor_insert_buttons.add_button(gtk.gdk.pixbuf_new_from_file(IMG_PATH + "overwrite_range.png"), tlineaction.range_overwrite_pressed)
editor_window.monitor_insert_buttons.add_button(gtk.gdk.pixbuf_new_from_file(IMG_PATH + "overwrite_clip.png"), tlineaction.three_point_overwrite_pressed)
editor_window.monitor_insert_buttons.add_button(gtk.gdk.pixbuf_new_from_file(IMG_PATH + "insert_clip.png"), tlineaction.insert_button_pressed)
editor_window.monitor_insert_buttons.add_button(gtk.gdk.pixbuf_new_from_file(IMG_PATH + "append_clip.png"), tlineaction.append_button_pressed)
editor_window.monitor_insert_buttons.widget.set_tooltip_text(_("Overwrite Range\nOverwrite Clip - T\nInsert Clip - Y\nAppend Clip - U"))
editor_window.undo_redo = glassbuttons.GlassButtonsGroup(46, 23, 2, 2, 7)
editor_window.undo_redo.add_button(gtk.gdk.pixbuf_new_from_file(IMG_PATH + "undo.png"), undo.do_undo_and_repaint)
editor_window.undo_redo.add_button(gtk.gdk.pixbuf_new_from_file(IMG_PATH + "redo.png"), undo.do_redo_and_repaint)
editor_window.undo_redo.widget.set_tooltip_text(_("Undo - Ctrl + X\nRedo - Ctrl + Y"))
editor_window.tools_buttons = glassbuttons.GlassButtonsGroup(46, 23, 2, 14, 7)
editor_window.tools_buttons.add_button(gtk.gdk.pixbuf_new_from_file(IMG_PATH + "open_mixer.png"), audiomonitoring.show_audio_monitor)
editor_window.tools_buttons.add_button(gtk.gdk.pixbuf_new_from_file(IMG_PATH + "open_titler.png"), titler.show_titler)
editor_window.tools_buttons.widget.set_tooltip_text(_("Audio Mixer\nTitler"))
if editorstate.audio_monitoring_available == False:
editor_window.tools_buttons.sensitive[0] = False
editor_window.tools_buttons.widget.set_tooltip_text(_("Audio Mixer(not available)\nTitler"))
editor_window.transition_button = glassbuttons.GlassButtonsGroup(46, 23, 2, 4, 5)
editor_window.transition_button.add_button(gtk.gdk.pixbuf_new_from_file(IMG_PATH + "dissolve.png"), tlineaction.add_transition_pressed)
editor_window.transition_button.widget.set_tooltip_text(_("Add Rendered Transition - 2 clips selected\nAdd Rendered Fade - 1 clip selected"))
def fill_with_TC_LEFT_pattern(buttons_row, window):
global w
w = window
buttons_row.pack_start(w.big_TC.widget, False, True, 0)
buttons_row.pack_start(guiutils.get_pad_label(7, MIDDLE_ROW_HEIGHT), False, True, 0) #### NOTE!!!!!! THIS DETERMINES THE HEIGHT OF MIDDLE ROW
buttons_row.pack_start(w.modes_selector.widget, False, True, 0)
buttons_row.pack_start(gtk.Label(), True, True, 0)
if editorstate.SCREEN_WIDTH > 1279:
buttons_row.pack_start(_get_tools_buttons(), False, True, 0)
buttons_row.pack_start(gtk.Label(), True, True, 0)
buttons_row.pack_start(_get_undo_buttons_panel(), False, True, 0)
buttons_row.pack_start(gtk.Label(), True, True, 0)
buttons_row.pack_start(_get_zoom_buttons_panel(),False, True, 0)
buttons_row.pack_start(gtk.Label(), True, True, 0)
buttons_row.pack_start(_get_edit_buttons_panel(),False, True, 0)
buttons_row.pack_start(gtk.Label(), True, True, 0)
buttons_row.pack_start(_get_transition_button(), False, True, 0)
buttons_row.pack_start(gtk.Label(), True, True, 0)
buttons_row.pack_start(_get_monitor_insert_buttons(), False, True, 0)
def fill_with_TC_MIDDLE_pattern(buttons_row, window):
global w
w = window
left_panel = gtk.HBox(False, 0)
left_panel.pack_start(_get_undo_buttons_panel(), False, True, 0)
left_panel.pack_start(guiutils.get_pad_label(10, MIDDLE_ROW_HEIGHT), False, True, 0) #### NOTE!!!!!! THIS DETERMINES THE HEIGHT OF MIDDLE ROW
left_panel.pack_start(_get_zoom_buttons_panel(), False, True, 0)
if editorstate.SCREEN_WIDTH > 1279:
left_panel.pack_start(guiutils.get_pad_label(10, 10), False, True, 0)
left_panel.pack_start(_get_tools_buttons(), False, True, 0)
left_panel.pack_start(guiutils.get_pad_label(50, 10), False, True, 10) # to left and right panel same size for centering
else:
left_panel.pack_start(guiutils.get_pad_label(60, 10), False, True, 10) # to left and right panel same size for centering
left_panel.pack_start(gtk.Label(), True, True, 0)
middle_panel = gtk.HBox(False, 0)
middle_panel.pack_start(w.big_TC.widget, False, True, 0)
middle_panel.pack_start(guiutils.get_pad_label(10, 10), False, True, 0)
middle_panel.pack_start(w.modes_selector.widget, False, True, 0)
right_panel = gtk.HBox(False, 0)
right_panel.pack_start(gtk.Label(), True, True, 0)
right_panel.pack_start(_get_edit_buttons_panel(), False, True, 0)
right_panel.pack_start(guiutils.get_pad_label(10, 10), False, True, 0)
right_panel.pack_start(_get_monitor_insert_buttons(), False, True, 0)
buttons_row.pack_start(left_panel, True, True, 0)
buttons_row.pack_start(middle_panel, False, False, 0)
buttons_row.pack_start(right_panel, True, True, 0)
# These get methods are unnecessery, unless we later make possible to use differnt kinds of buttons
def _get_mode_buttons_panel():
return w.mode_buttons_group.widget
def _get_zoom_buttons_panel():
return w.zoom_buttons.widget
def _get_undo_buttons_panel():
return w.undo_redo.widget
def _get_edit_buttons_panel():
return w.edit_buttons.widget
def _get_monitor_insert_buttons():
return w.monitor_insert_buttons.widget
def _get_tools_buttons():
return w.tools_buttons.widget
def _get_transition_button():
return w.transition_button.widget
def _get_buttons_panel(btns_count, btn_width=BUTTON_WIDTH):
panel = gtk.HBox(True, 0)
panel.set_size_request(btns_count * btn_width, BUTTON_HEIGHT)
return panel
def _b(button, icon, remove_relief=False):
button.set_image(icon)
button.set_property("can-focus", False)
if remove_relief:
button.set_relief(gtk.RELIEF_NONE)
def _clear_container(cont):
children = cont.get_children()
for child in children:
cont.remove(child)
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module holds current editor state.
Accessor methods are there mainly to improve code readability elsewhere.
We're using BIG_METHOD_NAMES() for state objects. This is a bit unusual
but looks good when reading code.
"""
import appconsts
# Edit modes
INSERT_MOVE = 0
OVERWRITE_MOVE = 1
ONE_ROLL_TRIM = 2
TWO_ROLL_TRIM = 3
SELECT_PARENT_CLIP = 4
COMPOSITOR_EDIT = 5
ONE_ROLL_TRIM_NO_EDIT = 6
TWO_ROLL_TRIM_NO_EDIT = 7
SLIDE_TRIM = 8
SLIDE_TRIM_NO_EDIT = 9
MULTI_MOVE = 10
# Project being edited
project = None
# Wrapped MLT framework producer->consumer media player
player = None
# Current edit mode
edit_mode = INSERT_MOVE
# Media files view filter for selecting displayed media objects in bin
media_view_filter = appconsts.SHOW_ALL_FILES
# Media file displayed in monitor when 'Clip' is pressed
_monitor_media_file = None
# Flag for timeline/clip display in monitor
_timeline_displayed = True
# Timeline current frame is saved here while clip is being displayed in monitor
# and PLAYER() current frame is not timeline frame
tline_shadow_frame = -1
# Dict of curren proxy media paths
_current_proxy_paths = {}
# Clips or compositor that are copy/pasted with CTRL+C, CTRL+V
_copy_paste_objects = None
# Used to alter gui layout and tracks configuration, set at startup
SCREEN_HEIGHT = -1
SCREEN_WIDTH = -1
# Runtime environment data
gtk_version = None
mlt_version = None
appversion = "0.10"
RUNNING_FROM_INSTALLATION = 0
RUNNING_FROM_DEV_VERSION = 1
app_running_from = RUNNING_FROM_INSTALLATION
audio_monitoring_available = False
# Cursor pos
cursor_on_tline = False
# Flag for running JACK audio server. If this is on when SDLConsumer created in mltplayer.py
# jack rack filter will bw taached to it
attach_jackrack = False
# Flag is used to block unwanted draw events during loads
project_is_loading = False
def current_is_move_mode():
if ((edit_mode == INSERT_MOVE) or (edit_mode == OVERWRITE_MOVE) or (edit_mode == MULTI_MOVE)):
return True
return False
def current_is_active_trim_mode():
if ((edit_mode == ONE_ROLL_TRIM) or (edit_mode == TWO_ROLL_TRIM) or (edit_mode == SLIDE_TRIM)):
return True
return False
def current_sequence():
return project.c_seq
def current_bin():
return project.c_bin
def current_proxy_media_paths():
return _current_proxy_paths
def update_current_proxy_paths():
global _current_proxy_paths
_current_proxy_paths = project.get_current_proxy_paths()
def current_tline_frame():
if timeline_visible():
return PLAYER().current_frame()
else:
return tline_shadow_frame
def PROJECT():
return project
def PLAYER():
return player
def EDIT_MODE():
return edit_mode
def MONITOR_MEDIA_FILE():
return _monitor_media_file
def get_track(index):
return project.c_seq.tracks[index]
def timeline_visible():
return _timeline_displayed
def mlt_version_is_equal_or_greater(test_version):
mlt_parts = mlt_version.split(".")
test_parts = test_version.split(".")
if test_parts[0] >= mlt_parts[0] and test_parts[1] >= mlt_parts[1] and test_parts[2] >= mlt_parts[2]:
return True
return False
def set_copy_paste_objects(objs):
global _copy_paste_objects
_copy_paste_objects = objs
def get_copy_paste_objects():
return _copy_paste_objects
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2014 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
import datetime
import gobject
import pygtk
pygtk.require('2.0');
import gtk
import dbus
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop
import mlt
import md5
import locale
import os
from os import listdir
from os.path import isfile, join
import pango
import pickle
import shutil
import subprocess
import sys
import textwrap
import time
import threading
import dialogutils
import editorstate
import editorpersistance
import guiutils
import mltenv
import mltprofiles
import mlttransitions
import mltfilters
import persistance
import respaths
import renderconsumer
import translations
import utils
BATCH_DIR = "batchrender/"
DATAFILES_DIR = "batchrender/datafiles/"
PROJECTS_DIR = "batchrender/projects/"
PID_FILE = "batchrenderingpid"
WINDOW_WIDTH = 800
QUEUE_HEIGHT = 400
IN_QUEUE = 0
RENDERING = 1
RENDERED = 2
UNQUEUED = 3
ABORTED = 4
render_queue = []
batch_window = None
render_thread = None
queue_runner_thread = None
timeout_id = None
_dbus_service = None
# -------------------------------------------------------- render thread
class QueueRunnerThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
self.running = True
items = 0
global render_queue, batch_window
for render_item in render_queue.queue:
if self.running == False:
break
if render_item.render_this_item == False:
continue
current_render_time = 0
# Create render objects
identifier = render_item.generate_identifier()
project_file_path = get_projects_dir() + identifier + ".flb"
persistance.show_messages = False
project = persistance.load_project(project_file_path, False)
producer = project.c_seq.tractor
consumer = renderconsumer.get_mlt_render_consumer(render_item.render_path,
project.profile,
render_item.args_vals_list)
# Get render range
start_frame, end_frame, wait_for_stop_render = get_render_range(render_item)
# Create and launch render thread
global render_thread
render_thread = renderconsumer.FileRenderPlayer(None, producer, consumer, start_frame, end_frame) # None == file name not needed this time when using FileRenderPlayer because callsite keeps track of things
render_thread.wait_for_producer_end_stop = wait_for_stop_render
render_thread.start()
# Set render start time and item state
render_item.render_started()
gtk.gdk.threads_enter()
batch_window.update_queue_view()
batch_window.current_render.set_text(" " + render_item.get_display_name())
gtk.gdk.threads_leave()
# Make sure that render thread is actually running before
# testing render_thread.running value later
while render_thread.has_started_running == False:
time.sleep(0.05)
# View update loop
self.thread_running = True
self.aborted = False
while self.thread_running:
if self.aborted == True:
break
render_fraction = render_thread.get_render_fraction()
now = time.time()
current_render_time = now - render_item.start_time
gtk.gdk.threads_enter()
batch_window.update_render_progress(render_fraction, items, render_item.get_display_name(), current_render_time)
gtk.gdk.threads_leave()
if render_thread.running == False: # Rendering has reached end
self.thread_running = False
gtk.gdk.threads_enter()
batch_window.render_progress_bar.set_fraction(1.0)
gtk.gdk.threads_leave()
render_item.render_completed()
else:
time.sleep(0.33)
if not self.aborted:
items = items + 1
gtk.gdk.threads_enter()
batch_window.update_render_progress(0, items, render_item.get_display_name(), 0)
gtk.gdk.threads_leave()
else:
if render_item != None:
render_item.render_aborted()
break
render_thread.shutdown()
# Update view for render end
gtk.gdk.threads_enter()
batch_window.reload_queue() # item may havee added to queue while rendering
batch_window.render_queue_stopped()
gtk.gdk.threads_leave()
def abort(self):
render_thread.shutdown()
# It may be that 'aborted' and 'running' could combined into single flag, but whatevaar
self.aborted = True
self.running = False
self.thread_running = False
batch_window.reload_queue() # item may havee added to queue while rendering
class BatchRenderDBUSService(dbus.service.Object):
def __init__(self):
print "dbus service init"
bus_name = dbus.service.BusName('flowblade.movie.editor.batchrender', bus=dbus.SessionBus())
dbus.service.Object.__init__(self, bus_name, '/flowblade/movie/editor/batchrender')
@dbus.service.method('flowblade.movie.editor.batchrender')
def render_item_added(self):
if queue_runner_thread == None:
batch_window.reload_queue()
return "OK"
@dbus.service.method('flowblade.movie.editor.batchrender')
def remove_from_dbus(self):
self.remove_from_connection()
return
# --------------------------------------------------- adding item, always called from main app
def add_render_item(flowblade_project, render_path, args_vals_list, mark_in, mark_out, render_data):
init_dirs_if_needed()
timestamp = datetime.datetime.now()
# Create item data file
project_name = flowblade_project.name
sequence_name = flowblade_project.c_seq.name
sequence_index = flowblade_project.sequences.index(flowblade_project.c_seq)
length = flowblade_project.c_seq.get_length()
render_item = BatchRenderItemData(project_name, sequence_name, render_path, \
sequence_index, args_vals_list, timestamp, length, \
mark_in, mark_out, render_data)
# Get identifier
identifier = render_item.generate_identifier()
# Write project
project_path = get_projects_dir() + identifier + ".flb"
persistance.save_project(flowblade_project, project_path)
# Write render item file
render_item.save()
bus = dbus.SessionBus()
if bus.name_has_owner('flowblade.movie.editor.batchrender'):
obj = bus.get_object('flowblade.movie.editor.batchrender', '/flowblade/movie/editor/batchrender')
iface = dbus.Interface(obj, 'flowblade.movie.editor.batchrender')
iface.render_item_added()
else:
launch_batch_rendering()
print "Render queue item for rendering file into " + render_path + " with identifier " + identifier + " added."
# ------------------------------------------------------- file utils
def init_dirs_if_needed():
user_dir = utils.get_hidden_user_dir_path()
if not os.path.exists(user_dir + BATCH_DIR):
os.mkdir(user_dir + BATCH_DIR)
if not os.path.exists(get_datafiles_dir()):
os.mkdir(get_datafiles_dir())
if not os.path.exists(get_projects_dir()):
os.mkdir(get_projects_dir())
def get_projects_dir():
return utils.get_hidden_user_dir_path() + PROJECTS_DIR
def get_datafiles_dir():
return utils.get_hidden_user_dir_path() + DATAFILES_DIR
def get_identifier_from_path(file_path):
start = file_path.rfind("/")
end = file_path.rfind(".")
return file_path[start + 1:end]
def _get_pid_file_path():
user_dir = utils.get_hidden_user_dir_path()
return user_dir + PID_FILE
def destroy_for_identifier(identifier):
try:
item_path = get_datafiles_dir() + identifier + ".renderitem"
os.remove(item_path)
except:
pass
try:
project_path = get_projects_dir() + identifier + ".flb"
os.remove(project_path)
except:
pass
def copy_project(render_item, file_name):
try:
shutil.copyfile(render_item.get_project_filepath(), file_name)
except Exception as e:
primary_txt = _("Render Item Project File Copy failed!")
secondary_txt = _("Error message: ") + str(e)
dialogutils.warning_message(primary_txt, secondary_txt, batch_window.window)
# --------------------------------------------------------------- app thread and data objects
def launch_batch_rendering():
bus = dbus.SessionBus()
if bus.name_has_owner('flowblade.movie.editor.batchrender'):
print "flowblade.movie.editor.batchrender dbus service exists, batch rendering already running"
_show_single_instance_info()
else:
FNULL = open(os.devnull, 'w')
subprocess.Popen([sys.executable, respaths.LAUNCH_DIR + "flowbladebatch"], stdin=FNULL, stdout=FNULL, stderr=FNULL)
def main(root_path, force_launch=False):
# Allow only on instance to run
#can_run = test_and_write_pid()
can_run = True
init_dirs_if_needed()
editorstate.gtk_version = gtk.gtk_version
try:
editorstate.mlt_version = mlt.LIBMLT_VERSION
except:
editorstate.mlt_version = "0.0.99" # magic string for "not found"
# Set paths.
respaths.set_paths(root_path)
# Init translations module with translations data
translations.init_languages()
translations.load_filters_translations()
mlttransitions.init_module()
# Load editor prefs and list of recent projects
editorpersistance.load()
# Init gtk threads
gtk.gdk.threads_init()
gtk.gdk.threads_enter()
repo = mlt.Factory().init()
# Set numeric locale to use "." as radix, MLT initilizes this to OS locale and this causes bugs
locale.setlocale(locale.LC_NUMERIC, 'C')
# Check for codecs and formats on the system
mltenv.check_available_features(repo)
renderconsumer.load_render_profiles()
# Load filter and compositor descriptions from xml files.
mltfilters.load_filters_xml(mltenv.services)
mlttransitions.load_compositors_xml(mltenv.transitions)
# Create list of available mlt profiles
mltprofiles.load_profile_list()
global render_queue
render_queue = RenderQueue()
render_queue.load_render_items()
global batch_window
batch_window = BatchRenderWindow()
if render_queue.error_status != None:
primary_txt = _("Error loading render queue items!")
secondary_txt = _("Message:\n") + render_queue.get_error_status_message()
dialogutils.warning_message(primary_txt, secondary_txt, batch_window.window)
DBusGMainLoop(set_as_default=True)
global _dbus_service
_dbus_service = BatchRenderDBUSService()
gtk.main()
gtk.gdk.threads_leave()
def _show_single_instance_info():
global timeout_id
timeout_id = gobject.timeout_add(200, _display_single_instance_window)
# Launch gtk+ main loop
gtk.main()
def _display_single_instance_window():
gobject.source_remove(timeout_id)
primary_txt = _("Batch Render Queue already running!")
msg = _("Batch Render Queue application was detected in session dbus.")
#msg = msg1 + msg2
content = dialogutils.get_warning_message_dialog_panel(primary_txt, msg, True)
align = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
align.set_padding(0, 12, 0, 0)
align.add(content)
dialog = gtk.Dialog("",
None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(_("OK").encode('utf-8'), gtk.RESPONSE_OK))
dialog.vbox.pack_start(align, True, True, 0)
dialogutils.default_behaviour(dialog)
dialog.connect('response', _early_exit)
dialog.show_all()
def _early_exit(dialog, response):
dialog.destroy()
gtk.main_quit()
def shutdown():
if queue_runner_thread != None:
primary_txt = _("Application is rendering and cannot be closed!")
secondary_txt = _("Stop rendering before closing the application.")
dialogutils.info_message(primary_txt, secondary_txt, batch_window.window)
return True # Tell callsite (inside GTK toolkit) that event is handled, otherwise it'll destroy window anyway.
while(gtk.events_pending()):
gtk.main_iteration()
if _dbus_service != None:
_dbus_service.remove_from_dbus()
gtk.main_quit()
class RenderQueue:
def __init__(self):
self.queue = []
self.error_status = None
def load_render_items(self):
self.queue = []
self.error_status = None
user_dir = utils.get_hidden_user_dir_path()
data_files_dir = user_dir + DATAFILES_DIR
data_files = [ f for f in listdir(data_files_dir) if isfile(join(data_files_dir,f)) ]
for data_file_name in data_files:
try:
data_file_path = data_files_dir + data_file_name
data_file = open(data_file_path)
render_item = pickle.load(data_file)
self.queue.append(render_item)
except Exception as e:
if self.error_status == None:
self.error_status = []
self.error_status.append((data_file_name, _(" datafile load failed with ") + str(e)))
try:
render_file = open(render_item.get_project_filepath())
except Exception as e:
if self.error_status == None:
self.error_status = []
self.error_status.append((render_item.get_project_filepath(), _(" project file load failed with ") + str(e)))
if self.error_status != None:
for file_path, error_str in self.error_status:
identifier = get_identifier_from_path(file_path)
destroy_for_identifier(identifier)
for render_item in self.queue:
if render_item.matches_identifier(identifier):
self.queue.remove(render_item)
break
# Latest added items displayed on top
self.queue.sort(key=lambda item: item.timestamp)
self.queue.reverse()
def get_error_status_message(self):
msg = ""
for file_path, error_str in self.error_status:
err_str_item = file_path + error_str
lines = textwrap.wrap(err_str_item, 80)
for line in lines:
msg = msg + line + "\n"
return msg
def check_for_same_paths(self):
same_paths = {}
path_counts = {}
queued = []
for render_item in self.queue:
if render_item.status == IN_QUEUE:
queued.append(render_item)
for render_item in queued:
try:
count = path_counts[render_item.render_path]
count = count + 1
path_counts[render_item.render_path] = count
except:
path_counts[render_item.render_path] = 1
for k,v in path_counts.iteritems():
if v > 1:
same_paths[k] = v
return same_paths
class BatchRenderItemData:
def __init__(self, project_name, sequence_name, render_path, sequence_index, \
args_vals_list, timestamp, length, mark_in, mark_out, render_data):
self.project_name = project_name
self.sequence_name = sequence_name
self.render_path = render_path
self.sequence_index = sequence_index
self.args_vals_list = args_vals_list
self.timestamp = timestamp
self.length = length
self.mark_in = mark_in
self.mark_out = mark_out
self.render_data = render_data
self.render_this_item = True
self.status = IN_QUEUE
self.start_time = -1
self.render_time = -1
def generate_identifier(self):
id_str = self.project_name + self.timestamp.ctime()
return md5.new(id_str).hexdigest()
def matches_identifier(self, identifier):
if self.generate_identifier() == identifier:
return True
else:
return False
def save(self):
item_path = get_datafiles_dir() + self.generate_identifier() + ".renderitem"
item_write_file = file(item_path, "wb")
pickle.dump(self, item_write_file)
def delete_from_queue(self):
identifier = self.generate_identifier()
item_path = get_datafiles_dir() + identifier + ".renderitem"
os.remove(item_path)
project_path = get_projects_dir() + identifier + ".flb"
os.remove(project_path)
render_queue.queue.remove(self)
def render_started(self):
self.status = RENDERING
self.start_time = time.time()
def render_completed(self):
self.status = RENDERED
self.render_this_item = False
self.render_time = time.time() - self.start_time
self.save()
def render_aborted(self):
self.status = ABORTED
self.render_this_item = False
self.render_time = -1
self.save()
global queue_runner_thread, render_thread
render_thread = None
queue_runner_thread = None
def get_status_string(self):
if self.status == IN_QUEUE:
return _("Queued")
elif self.status == RENDERING:
return _("Rendering")
elif self.status == RENDERED:
return _("Finished")
elif self.status == UNQUEUED:
return _("Unqueued")
else:
return _("Aborted")
def get_display_name(self):
return self.project_name + "/" + self.sequence_name
def get_render_time(self):
if self.render_time != -1:
return utils.get_time_str_for_sec_float(self.render_time)
else:
return "-"
def get_project_filepath(self):
return get_projects_dir() + self.generate_identifier() + ".flb"
class RenderData:
def __init__(self, enc_index, quality_index, user_args, profile_desc, profile_name, fps):
self.enc_index = enc_index
self.quality_index = quality_index
self.user_args = user_args
self.profile_desc = profile_desc
self.profile_name = profile_name
self.fps = fps
def get_render_range(render_item):
if render_item.mark_in < 0: # no range defined
start_frame = 0
end_frame = render_item.length - 1 #
wait_for_stop_render = True
elif render_item.mark_out < 0: # only start defined
start_frame = render_item.mark_in
end_frame = render_item.length - 1 #
wait_for_stop_render = True
else: # both start and end defined
start_frame = render_item.mark_in
end_frame = render_item.mark_out
wait_for_stop_render = False
return (start_frame, end_frame, wait_for_stop_render)
# -------------------------------------------------------------------- gui
class BatchRenderWindow:
def __init__(self):
# Window
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("delete-event", lambda w, e:shutdown())
app_icon = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "flowbladebatchappicon.png")
self.window.set_icon_list(app_icon)
self.est_time_left = gtk.Label()
self.current_render = gtk.Label()
self.current_render_time = gtk.Label()
est_r = guiutils.get_right_justified_box([guiutils.bold_label(_("Estimated Left:"))])
current_r = guiutils.get_right_justified_box([guiutils.bold_label(_("Current Render:"))])
current_r_t = guiutils.get_right_justified_box([guiutils.bold_label(_("Elapsed:"))])
est_r.set_size_request(250, 20)
current_r.set_size_request(250, 20)
current_r_t.set_size_request(250, 20)
info_vbox = gtk.VBox(False, 0)
info_vbox.pack_start(guiutils.get_left_justified_box([current_r, self.current_render]), False, False, 0)
info_vbox.pack_start(guiutils.get_left_justified_box([current_r_t, self.current_render_time]), False, False, 0)
info_vbox.pack_start(guiutils.get_left_justified_box([est_r, self.est_time_left]), False, False, 0)
self.items_rendered = gtk.Label()
items_r = gtk.Label(_("Items Rendered:"))
self.render_started_label = gtk.Label()
started_r = gtk.Label(_("Render Started:"))
bottom_info_vbox = gtk.HBox(True, 0)
bottom_info_vbox.pack_start(guiutils.get_left_justified_box([items_r, self.items_rendered]), True, True, 0)
bottom_info_vbox.pack_start(guiutils.get_left_justified_box([started_r, self.render_started_label]), True, True, 0)
self.not_rendering_txt = _("Not Rendering")
self.render_progress_bar = gtk.ProgressBar()
self.render_progress_bar.set_text(self.not_rendering_txt)
self.remove_selected = gtk.Button(_("Delete Selected"))
self.remove_selected.connect("clicked",
lambda w, e: self.remove_selected_clicked(),
None)
self.remove_finished = gtk.Button(_("Delete Finished"))
self.remove_finished.connect("clicked",
lambda w, e: self.remove_finished_clicked(),
None)
self.reload_button = gtk.Button(_("Reload Queue"))
self.reload_button.connect("clicked",
lambda w, e: self.reload_queue(),
None)
self.render_button = guiutils.get_render_button()
self.render_button.connect("clicked",
lambda w, e: self.launch_render(),
None)
self.stop_render_button = gtk.Button(_("Stop Render"))
self.stop_render_button.set_sensitive(False)
self.stop_render_button.connect("clicked",
lambda w, e: self.abort_render(),
None)
button_row = gtk.HBox(False, 0)
button_row.pack_start(self.remove_selected, False, False, 0)
button_row.pack_start(self.remove_finished, False, False, 0)
button_row.pack_start(gtk.Label(), True, True, 0)
#button_row.pack_start(self.reload_button, True, True, 0)
#button_row.pack_start(gtk.Label(), True, True, 0)
button_row.pack_start(self.stop_render_button, False, False, 0)
button_row.pack_start(self.render_button, False, False, 0)
top_vbox = gtk.VBox(False, 0)
top_vbox.pack_start(info_vbox, False, False, 0)
top_vbox.pack_start(guiutils.get_pad_label(12, 12), False, False, 0)
top_vbox.pack_start(self.render_progress_bar, False, False, 0)
top_vbox.pack_start(guiutils.get_pad_label(12, 12), False, False, 0)
top_vbox.pack_start(button_row, False, False, 0)
top_align = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
top_align.set_padding(12, 12, 12, 12)
top_align.add(top_vbox)
self.queue_view = RenderQueueView()
self.queue_view.fill_data_model(render_queue)
self.queue_view.set_size_request(WINDOW_WIDTH, QUEUE_HEIGHT)
bottom_align = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
bottom_align.set_padding(0, 2, 8, 8)
bottom_align.add(bottom_info_vbox)
# Content pane
pane = gtk.VBox(False, 1)
pane.pack_start(top_align, False, False, 0)
pane.pack_start(self.queue_view, True, True, 0)
pane.pack_start(bottom_align, False, False, 0)
# Set pane and show window
self.window.add(pane)
self.window.set_title(_("Flowblade Batch Render"))
self.window.set_position(gtk.WIN_POS_CENTER)
self.window.show_all()
def remove_finished_clicked(self):
delete_list = []
for render_item in render_queue.queue:
if render_item.status == RENDERED:
delete_list.append(render_item)
if len(delete_list) > 0:
self.display_delete_confirm(delete_list)
def remove_selected_clicked(self):
model, rows = self.queue_view.treeview.get_selection().get_selected_rows()
delete_list = []
for row in rows:
delete_list.append(render_queue.queue[max(row)])
if len(delete_list) > 0:
self.display_delete_confirm(delete_list)
def remove_item(self, render_item):
delete_list = []
delete_list.append(render_item)
self.display_delete_confirm(delete_list)
def display_delete_confirm(self, delete_list):
primary_txt = _("Delete ") + str(len(delete_list)) + _(" item(s) from render queue?")
secondary_txt = _("This operation cannot be undone.")
dialogutils.warning_confirmation(self._confirm_items_delete_callback, primary_txt, secondary_txt, self.window , data=delete_list, is_info=False)
def _confirm_items_delete_callback(self, dialog, response_id, delete_list):
if response_id == gtk.RESPONSE_ACCEPT:
for delete_item in delete_list:
delete_item.delete_from_queue()
self.update_queue_view()
dialog.destroy()
def reload_queue(self):
global render_queue
render_queue = RenderQueue()
render_queue.load_render_items()
if render_queue.error_status != None:
primary_txt = _("Error loading render queue items!")
secondary_txt = _("Message:\n") + render_queue.get_error_status_message()
dialogutils.warning_message(primary_txt, secondary_txt, batch_window.window)
return
self.queue_view.fill_data_model(render_queue)
def update_queue_view(self):
self.queue_view.fill_data_model(render_queue)
def launch_render(self):
same_paths = render_queue.check_for_same_paths()
if len(same_paths) > 0:
primary_txt = _("Multiple items with same render target file!")
secondary_txt = _("Later items will render on top of earlier items if this queue is rendered.\n") + \
_("Delete or unqueue some items with same paths:\n\n")
for k,v in same_paths.iteritems():
secondary_txt = secondary_txt + str(v) + _(" items with path: ") + str(k) + "\n"
dialogutils.warning_message(primary_txt, secondary_txt, batch_window.window)
return
# GUI pattern for rendering
self.render_button.set_sensitive(False)
self.reload_button.set_sensitive(False)
self.stop_render_button.set_sensitive(True)
self.est_time_left.set_text("")
self.items_rendered.set_text("")
start_time = datetime.datetime.now()
start_str = start_time.strftime(' %H:%M, %d %B, %Y')
self.render_started_label.set_text(start_str)
self.remove_selected.set_sensitive(False)
self.remove_finished.set_sensitive(False)
global queue_runner_thread
queue_runner_thread = QueueRunnerThread()
queue_runner_thread.start()
def update_render_progress(self, fraction, items, current_name, current_render_time_passed):
self.render_progress_bar.set_fraction(fraction)
progress_str = str(int(fraction * 100)) + " %"
self.render_progress_bar.set_text(progress_str)
if fraction != 0:
full_time_est = (1.0 / fraction) * current_render_time_passed
left_est = full_time_est - current_render_time_passed
est_str = " " + utils.get_time_str_for_sec_float(left_est)
else:
est_str = ""
self.est_time_left.set_text(est_str)
if current_render_time_passed != 0:
current_str= " " + utils.get_time_str_for_sec_float(current_render_time_passed)
else:
current_str = ""
self.current_render_time.set_text(current_str)
self.items_rendered.set_text(" " + str(items))
def abort_render(self):
global queue_runner_thread
queue_runner_thread.abort()
def render_queue_stopped(self):
self.render_progress_bar.set_fraction(0.0)
self.render_button.set_sensitive(True)
self.reload_button.set_sensitive(True)
self.stop_render_button.set_sensitive(False)
self.render_progress_bar.set_text(self.not_rendering_txt)
self.current_render.set_text("")
self.remove_selected.set_sensitive(True)
self.remove_finished.set_sensitive(True)
global queue_runner_thread, render_thread
render_thread = None
queue_runner_thread = None
class RenderQueueView(gtk.VBox):
def __init__(self):
gtk.VBox.__init__(self)
self.storemodel = gtk.ListStore(bool, str, str, str, str)
# Scroll container
self.scroll = gtk.ScrolledWindow()
self.scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
self.scroll.set_shadow_type(gtk.SHADOW_ETCHED_IN)
# View
self.treeview = gtk.TreeView(self.storemodel)
self.treeview.set_property("rules_hint", True)
self.treeview.set_headers_visible(True)
tree_sel = self.treeview.get_selection()
tree_sel.set_mode(gtk.SELECTION_MULTIPLE)
# Cell renderers
self.toggle_rend = gtk.CellRendererToggle()
self.toggle_rend.set_property('activatable', True)
self.toggle_rend.connect( 'toggled', self.toggled)
self.text_rend_1 = gtk.CellRendererText()
self.text_rend_1.set_property("ellipsize", pango.ELLIPSIZE_END)
self.text_rend_2 = gtk.CellRendererText()
self.text_rend_2.set_property("yalign", 0.0)
self.text_rend_3 = gtk.CellRendererText()
self.text_rend_3.set_property("yalign", 0.0)
self.text_rend_4 = gtk.CellRendererText()
self.text_rend_4.set_property("yalign", 0.0)
# Column views
self.toggle_col = gtk.TreeViewColumn(_("Render"), self.toggle_rend)
self.text_col_1 = gtk.TreeViewColumn(_("Project/Sequence"))
self.text_col_2 = gtk.TreeViewColumn(_("Status"))
self.text_col_3 = gtk.TreeViewColumn(_("Render File"))
self.text_col_4 = gtk.TreeViewColumn(_("Render Time"))
# Build column views
self.toggle_col.set_expand(False)
self.toggle_col.add_attribute(self.toggle_rend, "active", 0) # <- note column index
self.text_col_1.set_expand(True)
self.text_col_1.set_spacing(5)
self.text_col_1.set_sizing(gtk.TREE_VIEW_COLUMN_GROW_ONLY)
self.text_col_1.set_min_width(150)
self.text_col_1.pack_start(self.text_rend_1)
self.text_col_1.add_attribute(self.text_rend_1, "text", 1) # <- note column index
self.text_col_2.set_expand(False)
self.text_col_2.pack_start(self.text_rend_2)
self.text_col_2.add_attribute(self.text_rend_2, "text", 2)
self.text_col_3.set_expand(False)
self.text_col_3.pack_start(self.text_rend_3)
self.text_col_3.add_attribute(self.text_rend_3, "text", 3)
self.text_col_4.set_expand(False)
self.text_col_4.pack_start(self.text_rend_4)
self.text_col_4.add_attribute(self.text_rend_4, "text", 4)
# Add column views to view
self.treeview.append_column(self.toggle_col)
self.treeview.append_column(self.text_col_1)
self.treeview.append_column(self.text_col_2)
self.treeview.append_column(self.text_col_3)
self.treeview.append_column(self.text_col_4)
# popup menu
self.treeview.connect("button-press-event", self.on_treeview_button_press_event)
# Build widget graph and display
self.scroll.add(self.treeview)
self.pack_start(self.scroll)
self.scroll.show_all()
self.show_all()
def toggled(self, cell, path):
item_index = int(path)
global render_queue
render_queue.queue[item_index].render_this_item = not render_queue.queue[item_index].render_this_item
if render_queue.queue[item_index].render_this_item == True:
render_queue.queue[item_index].status = IN_QUEUE
else:
render_queue.queue[item_index].status = UNQUEUED
self.fill_data_model(render_queue)
def on_treeview_button_press_event(self, treeview, event):
if event.button == 3:
x = int(event.x)
y = int(event.y)
pthinfo = treeview.get_path_at_pos(x, y)
if pthinfo is not None:
path, col, cellx, celly = pthinfo
treeview.grab_focus()
treeview.set_cursor(path, col, 0)
display_render_item_popup_menu(self.item_menu_item_selected, event)
return True
else:
return False
def item_menu_item_selected(self, widget, msg):
model, rows = self.treeview.get_selection().get_selected_rows()
render_item = render_queue.queue[max(rows[0])]
if msg == "renderinfo":
show_render_properties_panel(render_item)
elif msg == "delete":
batch_window.remove_item(render_item)
elif msg == "saveas":
file_name = run_save_project_as_dialog(render_item.project_name)
if file_name != None:
copy_project(render_item, file_name)
def fill_data_model(self, render_queue):
self.storemodel.clear()
for render_item in render_queue.queue:
row_data = [render_item.render_this_item,
render_item.get_display_name(),
render_item.get_status_string(),
render_item.render_path,
render_item.get_render_time()]
self.storemodel.append(row_data)
self.scroll.queue_draw()
def run_save_project_as_dialog(project_name):
dialog = gtk.FileChooserDialog(_("Save Render Item Project As"), None,
gtk.FILE_CHOOSER_ACTION_SAVE,
(_("Cancel").encode('utf-8'), gtk.RESPONSE_REJECT,
_("Save").encode('utf-8'), gtk.RESPONSE_ACCEPT), None)
dialog.set_action(gtk.FILE_CHOOSER_ACTION_SAVE)
project_name = project_name.rstrip(".flb")
dialog.set_current_name(project_name + "_FROM_BATCH.flb")
dialog.set_do_overwrite_confirmation(True)
response_id = dialog.run()
if response_id == gtk.RESPONSE_NONE:
dialog.destroy()
return None
file_name = dialog.get_filename()
dialog.destroy()
return file_name
def show_render_properties_panel(render_item):
if render_item.render_data.user_args == False:
enc_opt = renderconsumer.encoding_options[render_item.render_data.enc_index]
enc_desc = enc_opt.name
audio_desc = enc_opt.audio_desc
quality_opt = enc_opt.quality_options[render_item.render_data.quality_index]
quality_desc = quality_opt.name
else:
enc_desc = " -"
quality_desc = " -"
audio_desc = " -"
user_args = str(render_item.render_data.user_args)
start_frame, end_frame, wait_for_stop_render = get_render_range(render_item)
start_str = utils.get_tc_string_with_fps(start_frame, render_item.render_data.fps)
end_str = utils.get_tc_string_with_fps(end_frame, render_item.render_data.fps)
LEFT_WIDTH = 200
render_item.get_display_name()
row0 = guiutils.get_two_column_box(guiutils.bold_label(_("Encoding:")), gtk.Label(enc_desc), LEFT_WIDTH)
row1 = guiutils.get_two_column_box(guiutils.bold_label(_("Quality:")), gtk.Label(quality_desc), LEFT_WIDTH)
row2 = guiutils.get_two_column_box(guiutils.bold_label(_("Audio Encoding:")), gtk.Label(audio_desc), LEFT_WIDTH)
row3 = guiutils.get_two_column_box(guiutils.bold_label(_("Use User Args:")), gtk.Label(user_args), LEFT_WIDTH)
row4 = guiutils.get_two_column_box(guiutils.bold_label(_("Start:")), gtk.Label(start_str), LEFT_WIDTH)
row5 = guiutils.get_two_column_box(guiutils.bold_label(_("End:")), gtk.Label(end_str), LEFT_WIDTH)
row6 = guiutils.get_two_column_box(guiutils.bold_label(_("Frames Per Second:")), gtk.Label(str(render_item.render_data.fps)), LEFT_WIDTH)
row7 = guiutils.get_two_column_box(guiutils.bold_label(_("Render Profile Name:")), gtk.Label(str(render_item.render_data.profile_name)), LEFT_WIDTH)
row8 = guiutils.get_two_column_box(guiutils.bold_label(_("Render Profile:")), gtk.Label(render_item.render_data.profile_desc), LEFT_WIDTH)
vbox = gtk.VBox(False, 2)
vbox.pack_start(gtk.Label(render_item.get_display_name()), False, False, 0)
vbox.pack_start(guiutils.get_pad_label(12, 16), False, False, 0)
vbox.pack_start(row0, False, False, 0)
vbox.pack_start(row1, False, False, 0)
vbox.pack_start(row2, False, False, 0)
vbox.pack_start(row3, False, False, 0)
vbox.pack_start(row4, False, False, 0)
vbox.pack_start(row5, False, False, 0)
vbox.pack_start(row6, False, False, 0)
vbox.pack_start(row7, False, False, 0)
vbox.pack_start(row8, False, False, 0)
vbox.pack_start(gtk.Label(), True, True, 0)
title = _("Render Properties")
dialogutils.panel_ok_dialog(title, vbox)
def display_render_item_popup_menu(callback, event):
menu = gtk.Menu()
menu.add(_get_menu_item(_("Save Item Project As..."), callback,"saveas"))
menu.add(_get_menu_item(_("Render Properties"), callback,"renderinfo"))
_add_separetor(menu)
menu.add(_get_menu_item(_("Delete"), callback,"delete"))
menu.popup(None, None, None, event.button, event.time)
def _add_separetor(menu):
sep = gtk.SeparatorMenuItem()
sep.show()
menu.add(sep)
def _get_menu_item(text, callback, data, sensitive=True):
item = gtk.MenuItem(text)
item.connect("activate", callback, data)
item.show()
item.set_sensitive(sensitive)
return item
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
import pygtk
pygtk.require('2.0');
import gtk
def load_titler_data_dialog(callback):
dialog = gtk.FileChooserDialog(_("Select Titler Data File"), None,
gtk.FILE_CHOOSER_ACTION_OPEN,
(_("Cancel").encode('utf-8'), gtk.RESPONSE_REJECT,
_("OK").encode('utf-8'), gtk.RESPONSE_ACCEPT), None)
dialog.set_action(gtk.FILE_CHOOSER_ACTION_OPEN)
dialog.set_select_multiple(False)
dialog.connect('response', callback)
dialog.show()
def save_titler_data_as_dialog(callback, current_name, open_dir):
dialog = gtk.FileChooserDialog(_("Save Titler Layers As"), None,
gtk.FILE_CHOOSER_ACTION_SAVE,
(_("Cancel").encode('utf-8'), gtk.RESPONSE_REJECT,
_("Save").encode('utf-8'), gtk.RESPONSE_ACCEPT), None)
dialog.set_action(gtk.FILE_CHOOSER_ACTION_SAVE)
dialog.set_current_name(current_name)
dialog.set_do_overwrite_confirmation(True)
if open_dir != None:
dialog.set_current_folder(open_dir)
dialog.set_select_multiple(False)
dialog.connect('response', callback)
dialog.show()
def save_titler_graphic_as_dialog(callback, current_name, open_dir):
dialog = gtk.FileChooserDialog(_("Save Titler Graphic As"), None,
gtk.FILE_CHOOSER_ACTION_SAVE,
(_("Cancel").encode('utf-8'), gtk.RESPONSE_REJECT,
_("Save").encode('utf-8'), gtk.RESPONSE_ACCEPT), None)
dialog.set_action(gtk.FILE_CHOOSER_ACTION_SAVE)
dialog.set_current_name(current_name)
dialog.set_do_overwrite_confirmation(True)
if open_dir != None:
dialog.set_current_folder(open_dir)
dialog.set_select_multiple(False)
file_filter = gtk.FileFilter()
file_filter.add_pattern("*" + ".png")
dialog.add_filter(file_filter)
dialog.connect('response', callback)
dialog.show()
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
import copy
import pygtk
pygtk.require('2.0');
import gtk
import glib
import os
import pango
import pangocairo
import pickle
import threading
import time
import toolsdialogs
from editorstate import PLAYER
from editorstate import PROJECT
import editorstate
import editorpersistance
import gui
import guicomponents
import guiutils
import dialogutils
import projectaction
import respaths
import positionbar
import utils
import vieweditor
import vieweditorlayer
_titler = None
_titler_data = None
_keep_titler_data = True
_open_saved_in_bin = True
VIEW_EDITOR_WIDTH = 815
VIEW_EDITOR_HEIGHT = 620
TEXT_LAYER_LIST_WIDTH = 300
TEXT_LAYER_LIST_HEIGHT = 250
TEXT_VIEW_WIDTH = 300
TEXT_VIEW_HEIGHT = 275
DEFAULT_FONT_SIZE = 25
FACE_REGULAR = "Regular"
FACE_BOLD = "Bold"
FACE_ITALIC = "Italic"
FACE_BOLD_ITALIC = "Bold Italic"
ALIGN_LEFT = 0
ALIGN_CENTER = 1
ALIGN_RIGHT = 2
def show_titler():
global _titler_data
if _titler_data == None:
_titler_data = TitlerData()
global _titler
if _titler != None:
primary_txt = _("Titler is already open")
secondary_txt = _("Only single instance of Titler can be opened.")
dialogutils.info_message(primary_txt, secondary_txt, gui.editor_window.window)
return
_titler = Titler()
_titler.load_titler_data()
_titler.show_current_frame()
def close_titler():
global _titler, _titler_data
_titler.set_visible(False)
glib.idle_add(titler_destroy)
def titler_destroy():
global _titler, _titler_data
_titler.destroy()
_titler = None
if not _keep_titler_data:
_titler_data = None
# ------------------------------------------------------------- data
class TextLayer:
"""
Data needed to create a pango text layout.
"""
def __init__(self):
self.text = "Text"
self.x = 0.0
self.y = 0.0
self.angle = 0.0 # future feature
self.font_family = "Times New Roman"
self.font_face = FACE_REGULAR
self.font_size = 15
self.color_rgba = (1.0, 1.0, 1.0, 1.0)
self.alignment = ALIGN_LEFT
self.pixel_size = (100, 100)
self.spacing = 5
self.pango_layout = None # PangoTextLayout(self)
self.drop_shadow = None # future feature, here to keep file compat once added
self.animation = None # future feature
self.layer_attributes = None # future feature (kerning etc. go here, we're not using all pango features)
self.visible = True
def get_font_desc_str(self):
return self.font_family + " " + self.font_face + " " + str(self.font_size)
def update_pango_layout(self):
self.pango_layout.load_layer_data(self)
class TitlerData:
"""
Data edited in titler editor
"""
def __init__(self):
self.layers = []
self.active_layer = None
self.add_layer()
self.scroll_params = None # future feature
def add_layer(self):
# adding layer makes new layer active
self.active_layer = TextLayer()
self.active_layer.pango_layout = PangoTextLayout(self.active_layer)
self.layers.append(self.active_layer)
def get_active_layer_index(self):
return self.layers.index(self.active_layer)
def save(self, save_file_path):
save_data = copy.deepcopy(self)
for layer in save_data.layers:
layer.pango_layout = None
write_file = file(save_file_path, "wb")
pickle.dump(save_data, write_file)
def create_pango_layouts(self):
for layer in self.layers:
layer.pango_layout = PangoTextLayout(layer)
# ---------------------------------------------------------- editor
class Titler(gtk.Window):
def __init__(self):
gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
self.set_title(_("Titler"))
self.connect("delete-event", lambda w, e:close_titler())
if editorstate.SCREEN_HEIGHT < 800:
global TEXT_LAYER_LIST_HEIGHT, TEXT_VIEW_HEIGHT, VIEW_EDITOR_HEIGHT
TEXT_LAYER_LIST_HEIGHT = 200
TEXT_VIEW_HEIGHT = 225
VIEW_EDITOR_HEIGHT = 550
self.block_updates = False
self.view_editor = vieweditor.ViewEditor(PLAYER().profile, VIEW_EDITOR_WIDTH, VIEW_EDITOR_HEIGHT)
self.view_editor.active_layer_changed_listener = self.active_layer_changed
self.guides_toggle = vieweditor.GuidesViewToggle(self.view_editor)
add_b = gtk.Button(_("Add"))
del_b = gtk.Button(_("Delete"))
add_b.connect("clicked", lambda w:self._add_layer_pressed())
del_b.connect("clicked", lambda w:self._del_layer_pressed())
add_del_box = gtk.HBox()
add_del_box = gtk.HBox(True,1)
add_del_box.pack_start(add_b)
add_del_box.pack_start(del_b)
center_h_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "center_horizontal.png")
center_v_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "center_vertical.png")
center_h = gtk.Button()
center_h.set_image(center_h_icon)
center_h.connect("clicked", lambda w:self._center_h_pressed())
center_v = gtk.Button()
center_v.set_image(center_v_icon)
center_v.connect("clicked", lambda w:self._center_v_pressed())
self.layer_list = TextLayerListView(self._layer_selection_changed, self._layer_visibility_toggled)
self.layer_list.set_size_request(TEXT_LAYER_LIST_WIDTH, TEXT_LAYER_LIST_HEIGHT)
self.text_view = gtk.TextView()
self.text_view.set_pixels_above_lines(2)
self.text_view.set_left_margin(2)
self.text_view.get_buffer().connect("changed", self._text_changed)
self.sw = gtk.ScrolledWindow()
self.sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
self.sw.add(self.text_view)
self.sw.set_size_request(TEXT_VIEW_WIDTH, TEXT_VIEW_HEIGHT)
scroll_frame = gtk.Frame()
scroll_frame.add(self.sw)
self.tc_display = guicomponents.MonitorTCDisplay()
self.tc_display.use_internal_frame = True
self.pos_bar = positionbar.PositionBar()
self.pos_bar.set_listener(self.position_listener)
self.pos_bar.update_display_from_producer(PLAYER().producer)
self.pos_bar.mouse_release_listener = self.pos_bar_mouse_released
pos_bar_frame = gtk.Frame()
pos_bar_frame.add(self.pos_bar.widget)
pos_bar_frame.set_shadow_type(gtk.SHADOW_ETCHED_IN)
font_map = pangocairo.cairo_font_map_get_default()
unsorted_families = font_map.list_families()
if len(unsorted_families) == 0:
print "No font families found in system! Titler will not work."
self.font_families = sorted(unsorted_families, key=lambda family: family.get_name())
self.font_family_indexes_for_name = {}
combo = gtk.combo_box_new_text()
indx = 0
for family in self.font_families:
combo.append_text(family.get_name())
self.font_family_indexes_for_name[family.get_name()] = indx
indx += 1
combo.set_active(0)
self.font_select = combo
self.font_select.connect("changed", self._edit_value_changed)
adj = gtk.Adjustment(float(DEFAULT_FONT_SIZE), float(1), float(300), float(1))
self.size_spin = gtk.SpinButton(adj)
self.size_spin.connect("changed", self._edit_value_changed)
self.size_spin.connect("key-press-event", self._key_pressed_on_widget)
font_main_row = gtk.HBox()
font_main_row.pack_start(self.font_select, True, True, 0)
font_main_row.pack_start(guiutils.pad_label(5, 5), False, False, 0)
font_main_row.pack_start(self.size_spin, False, False, 0)
self.bold_font = gtk.ToggleButton()
self.italic_font = gtk.ToggleButton()
bold_icon = gtk.image_new_from_stock(gtk.STOCK_BOLD,
gtk.ICON_SIZE_BUTTON)
italic_icon = gtk.image_new_from_stock(gtk.STOCK_ITALIC,
gtk.ICON_SIZE_BUTTON)
self.bold_font.set_image(bold_icon)
self.italic_font.set_image(italic_icon)
self.bold_font.connect("clicked", self._edit_value_changed)
self.italic_font.connect("clicked", self._edit_value_changed)
self.left_align = gtk.RadioButton()
self.center_align = gtk.RadioButton(self.left_align)
self.right_align = gtk.RadioButton(self.left_align)
left_icon = gtk.image_new_from_stock(gtk.STOCK_JUSTIFY_LEFT,
gtk.ICON_SIZE_BUTTON)
center_icon = gtk.image_new_from_stock(gtk.STOCK_JUSTIFY_CENTER,
gtk.ICON_SIZE_BUTTON)
right_icon = gtk.image_new_from_stock(gtk.STOCK_JUSTIFY_RIGHT,
gtk.ICON_SIZE_BUTTON)
self.left_align.set_image(left_icon)
self.center_align.set_image(center_icon)
self.right_align.set_image(right_icon)
self.left_align.set_mode(False)
self.center_align.set_mode(False)
self.right_align.set_mode(False)
self.left_align.connect("clicked", self._edit_value_changed)
self.center_align.connect("clicked", self._edit_value_changed)
self.right_align.connect("clicked", self._edit_value_changed)
self.color_button = gtk.ColorButton()
self.color_button.connect("color-set", self._edit_value_changed)
buttons_box = gtk.HBox()
buttons_box.pack_start(gtk.Label(), True, True, 0)
buttons_box.pack_start(self.bold_font, False, False, 0)
buttons_box.pack_start(self.italic_font, False, False, 0)
buttons_box.pack_start(guiutils.pad_label(5, 5), False, False, 0)
buttons_box.pack_start(self.left_align, False, False, 0)
buttons_box.pack_start(self.center_align, False, False, 0)
buttons_box.pack_start(self.right_align, False, False, 0)
buttons_box.pack_start(guiutils.pad_label(5, 5), False, False, 0)
buttons_box.pack_start(self.color_button, False, False, 0)
buttons_box.pack_start(gtk.Label(), True, True, 0)
load_layers = gtk.Button(_("Load Layers"))
load_layers.connect("clicked", lambda w:self._load_layers_pressed())
save_layers = gtk.Button(_("Save Layers"))
save_layers.connect("clicked", lambda w:self._save_layers_pressed())
clear_layers = gtk.Button(_("Clear All"))
clear_layers.connect("clicked", lambda w:self._clear_layers_pressed())
layers_save_buttons_row = gtk.HBox()
layers_save_buttons_row.pack_start(save_layers, False, False, 0)
layers_save_buttons_row.pack_start(load_layers, False, False, 0)
layers_save_buttons_row.pack_start(gtk.Label(), True, True, 0)
#layers_save_buttons_row.pack_start(clear_layers, False, False, 0)
adj = gtk.Adjustment(float(0), float(0), float(3000), float(1))
self.x_pos_spin = gtk.SpinButton(adj)
self.x_pos_spin.connect("changed", self._position_value_changed)
self.x_pos_spin.connect("key-press-event", self._key_pressed_on_widget)
adj = gtk.Adjustment(float(0), float(0), float(3000), float(1))
self.y_pos_spin = gtk.SpinButton(adj)
self.y_pos_spin.connect("changed", self._position_value_changed)
self.y_pos_spin.connect("key-press-event", self._key_pressed_on_widget)
adj = gtk.Adjustment(float(0), float(0), float(3000), float(1))
self.rotation_spin = gtk.SpinButton(adj)
self.rotation_spin.connect("changed", self._position_value_changed)
self.rotation_spin.connect("key-press-event", self._key_pressed_on_widget)
undo_pos = gtk.Button()
undo_icon = gtk.image_new_from_stock(gtk.STOCK_UNDO,
gtk.ICON_SIZE_BUTTON)
undo_pos.set_image(undo_icon)
next_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "next_frame_s.png")
prev_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "prev_frame_s.png")
prev_frame = gtk.Button()
prev_frame.set_image(prev_icon)
prev_frame.connect("clicked", lambda w:self._prev_frame_pressed())
next_frame = gtk.Button()
next_frame.set_image(next_icon)
next_frame.connect("clicked", lambda w:self._next_frame_pressed())
self.scale_selector = vieweditor.ScaleSelector(self)
timeline_box = gtk.HBox()
timeline_box.pack_start(guiutils.get_in_centering_alignment(self.tc_display.widget), False, False, 0)
timeline_box.pack_start(guiutils.get_in_centering_alignment(pos_bar_frame, 1.0), True, True, 0)
timeline_box.pack_start(prev_frame, False, False, 0)
timeline_box.pack_start(next_frame, False, False, 0)
timeline_box.pack_start(self.guides_toggle, False, False, 0)
timeline_box.pack_start(self.scale_selector, False, False, 0)
positions_box = gtk.HBox()
positions_box.pack_start(gtk.Label(), True, True, 0)
positions_box.pack_start(gtk.Label("X:"), False, False, 0)
positions_box.pack_start(self.x_pos_spin, False, False, 0)
positions_box.pack_start(guiutils.pad_label(10, 5), False, False, 0)
positions_box.pack_start(gtk.Label("Y:"), False, False, 0)
positions_box.pack_start(self.y_pos_spin, False, False, 0)
positions_box.pack_start(guiutils.pad_label(10, 5), False, False, 0)
#positions_box.pack_start(gtk.Label(_("Angle")), False, False, 0)
#positions_box.pack_start(self.rotation_spin, False, False, 0)
positions_box.pack_start(guiutils.pad_label(10, 5), False, False, 0)
positions_box.pack_start(center_h, False, False, 0)
positions_box.pack_start(center_v, False, False, 0)
positions_box.pack_start(gtk.Label(), True, True, 0)
controls_panel_1 = gtk.VBox()
controls_panel_1.pack_start(add_del_box, False, False, 0)
controls_panel_1.pack_start(self.layer_list, False, False, 0)
controls_panel_1.pack_start(layers_save_buttons_row, False, False, 0)
controls_panel_2 = gtk.VBox()
controls_panel_2.pack_start(scroll_frame, True, True, 0)
controls_panel_2.pack_start(font_main_row, False, False, 0)
controls_panel_2.pack_start(buttons_box, False, False, 0)
controls_panel = gtk.VBox()
controls_panel.pack_start(guiutils.get_named_frame(_("Active Layer"),controls_panel_2), True, True, 0)
controls_panel.pack_start(guiutils.get_named_frame(_("Layers"),controls_panel_1), False, False, 0)
view_editor_editor_buttons_row = gtk.HBox()
view_editor_editor_buttons_row.pack_start(positions_box, False, False, 0)
view_editor_editor_buttons_row.pack_start(gtk.Label(), True, True, 0)
keep_label = gtk.Label(_("Keep Layers When Closed"))
self.keep_layers_check = gtk.CheckButton()
self.keep_layers_check.set_active(_keep_titler_data)
self.keep_layers_check.connect("toggled", self._keep_layers_toggled)
open_label = gtk.Label(_("Open Saved Title In Bin"))
self.open_in_current_check = gtk.CheckButton()
self.open_in_current_check.set_active(_open_saved_in_bin)
self.open_in_current_check.connect("toggled", self._open_saved_in_bin)
exit_b = guiutils.get_sized_button(_("Close"), 150, 32)
exit_b.connect("clicked", lambda w:close_titler())
save_titles_b = guiutils.get_sized_button(_("Save Title Graphic"), 150, 32)
save_titles_b.connect("clicked", lambda w:self._save_title_pressed())
editor_buttons_row = gtk.HBox()
editor_buttons_row.pack_start(gtk.Label(), True, True, 0)
editor_buttons_row.pack_start(keep_label, False, False, 0)
editor_buttons_row.pack_start(self.keep_layers_check, False, False, 0)
editor_buttons_row.pack_start(guiutils.pad_label(24, 2), False, False, 0)
editor_buttons_row.pack_start(open_label, False, False, 0)
editor_buttons_row.pack_start(self.open_in_current_check, False, False, 0)
editor_buttons_row.pack_start(guiutils.pad_label(24, 2), False, False, 0)
editor_buttons_row.pack_start(exit_b, False, False, 0)
editor_buttons_row.pack_start(save_titles_b, False, False, 0)
editor_panel = gtk.VBox()
editor_panel.pack_start(self.view_editor, True, True, 0)
editor_panel.pack_start(timeline_box, False, False, 0)
editor_panel.pack_start(guiutils.get_in_centering_alignment(view_editor_editor_buttons_row), False, False, 0)
editor_panel.pack_start(guiutils.pad_label(2, 24), False, False, 0)
editor_panel.pack_start(editor_buttons_row, False, False, 0)
editor_row = gtk.HBox()
editor_row.pack_start(controls_panel, False, False, 0)
editor_row.pack_start(editor_panel, True, True, 0)
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(8,8,8,8)
alignment.add(editor_row)
self.add(alignment)
self.layer_list.fill_data_model()
self._update_gui_with_active_layer_data()
self.show_all()
self.connect("size-allocate", lambda w, e:self.window_resized())
self.connect("window-state-event", lambda w, e:self.window_resized())
def load_titler_data(self):
# clear and then load layers, and set layer 0 active
self.view_editor.clear_layers()
global _titler_data
_titler_data.create_pango_layouts()
for layer in _titler_data.layers:
text_layer = vieweditorlayer.TextEditLayer(self.view_editor, layer.pango_layout)
text_layer.mouse_released_listener = self._editor_layer_mouse_released
text_layer.set_rect_pos(layer.x, layer.y)
text_layer.update_rect = True
self.view_editor.add_layer(text_layer)
self._activate_layer(0)
self.layer_list.fill_data_model()
self.view_editor.edit_area.queue_draw()
def show_current_frame(self):
frame = PLAYER().current_frame()
length = PLAYER().producer.get_length()
rgbdata = PLAYER().seek_and_get_rgb_frame(frame)
self.view_editor.set_screen_rgb_data(rgbdata)
self.pos_bar.set_normalized_pos(float(frame)/float(length))
self.tc_display.set_frame(frame)
self.pos_bar.widget.queue_draw()
self._update_active_layout()
def window_resized(self):
scale = self.scale_selector.get_current_scale()
self.scale_changed(scale)
def scale_changed(self, new_scale):
self.view_editor.set_scale_and_update(new_scale)
self.view_editor.edit_area.queue_draw()
def write_current_frame(self):
self.view_editor.write_out_layers = True
self.show_current_frame()
def position_listener(self, normalized_pos, length):
frame = normalized_pos * length
self.tc_display.set_frame(int(frame))
self.pos_bar.widget.queue_draw()
def pos_bar_mouse_released(self, normalized_pos, length):
frame = int(normalized_pos * length)
PLAYER().seek_frame(frame)
self.show_current_frame()
def _save_title_pressed(self):
toolsdialogs.save_titler_graphic_as_dialog(self._save_title_dialog_callback, "title.png", None)
def _save_title_dialog_callback(self, dialog, response_id):
if response_id == gtk.RESPONSE_ACCEPT:
try:
filenames = dialog.get_filenames()
dialog.destroy()
save_path = filenames[0]
self.view_editor.write_layers_to_png(save_path)
if _open_saved_in_bin:
open_file_thread = OpenFileThread(save_path, self.view_editor)
open_file_thread.start()
# INFOWINDOW
except:
# INFOWINDOW
dialog.destroy()
return
else:
dialog.destroy()
def _save_layers_pressed(self):
toolsdialogs.save_titler_data_as_dialog(self._save_layers_dialog_callback, "titler_layers", None)
def _save_layers_dialog_callback(self, dialog, response_id):
if response_id == gtk.RESPONSE_ACCEPT:
filenames = dialog.get_filenames()
save_path = filenames[0]
_titler_data.save(save_path)
dialog.destroy()
else:
dialog.destroy()
def _load_layers_pressed(self):
toolsdialogs.load_titler_data_dialog(self._load_layers_dialog_callback)
def _load_layers_dialog_callback(self, dialog, response_id):
if response_id == gtk.RESPONSE_ACCEPT:
try:
filenames = dialog.get_filenames()
load_path = filenames[0]
f = open(load_path)
new_data = pickle.load(f)
global _titler_data
_titler_data = new_data
self.load_titler_data()
except:
dialog.destroy()
# INFOWINDOW
return
dialog.destroy()
else:
dialog.destroy()
def _clear_layers_pressed(self):
# INFOWINDOW
# CONFIRM WINDOW HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
global _titler_data
_titler_data = TitlerData()
self.load_titler_data()
def _keep_layers_toggled(self, widget):
global _keep_titler_data
_keep_titler_data = widget.get_active()
def _open_saved_in_bin(self, widget):
global _open_saved_in_bin
_open_saved_in_bin = widget.get_active()
def _key_pressed_on_widget(self, widget, event):
# update layer for enter on size spin
if widget == self.size_spin and event.keyval == gtk.keysyms.Return:
self.size_spin.update()
self._update_active_layout()
return True
# update layer for enter on x, y, angle
if ((event.keyval == gtk.keysyms.Return) and ((widget == self.x_pos_spin) or
(widget == self.y_pos_spin) or (widget == self.rotation_spin))):
self.x_pos_spin.update()
self.y_pos_spin.update()
self.rotation_spin.update()
_titler_data.active_layer.x = self.x_pos_spin.get_value()
_titler_data.active_layer.y = self.y_pos_spin.get_value()
self._update_editor_layer_pos()
self.view_editor.edit_area.queue_draw()
return True
return False
def _update_editor_layer_pos(self):
shape = self.view_editor.active_layer.edit_point_shape
shape.translate_points_to_pos(_titler_data.active_layer.x,
_titler_data.active_layer.y, 0)
def _add_layer_pressed(self):
global _titler_data
_titler_data.add_layer()
view_editor_layer = vieweditorlayer.TextEditLayer(self.view_editor, _titler_data.active_layer.pango_layout)
view_editor_layer.mouse_released_listener = self._editor_layer_mouse_released
self.view_editor.edit_layers.append(view_editor_layer)
self.layer_list.fill_data_model()
self._activate_layer(len(_titler_data.layers) - 1)
def _del_layer_pressed(self):
# we always need 1 layer
if len(_titler_data.layers) < 2:
return
#active_index = _titler_data.get_active_layer_index()
_titler_data.layers.remove(_titler_data.active_layer)
self.view_editor.edit_layers.remove(self.view_editor.active_layer)
self.layer_list.fill_data_model()
self._activate_layer(0)
def _layer_visibility_toggled(self, layer_index):
toggled_visible = (self.view_editor.edit_layers[layer_index].visible == False)
self.view_editor.edit_layers[layer_index].visible = toggled_visible
_titler_data.layers[layer_index].visible = toggled_visible
self.layer_list.fill_data_model()
self.view_editor.edit_area.queue_draw()
def _center_h_pressed(self):
# calculate top left x pos for centering
w, h = _titler_data.active_layer.pango_layout.pixel_size
centered_x = self.view_editor.profile_w/2 - w/2
# update data and view
_titler_data.active_layer.x = centered_x
self._update_editor_layer_pos()
self.view_editor.edit_area.queue_draw()
self.block_updates = True
self.x_pos_spin.set_value(centered_x)
self.block_updates = False
def _center_v_pressed(self):
# calculate top left x pos for centering
w, h = _titler_data.active_layer.pango_layout.pixel_size
centered_y = self.view_editor.profile_h/2 - h/2
# update data and view
_titler_data.active_layer.y = centered_y
self._update_editor_layer_pos()
self.view_editor.edit_area.queue_draw()
self.block_updates = True
self.y_pos_spin.set_value(centered_y)
self.block_updates = False
def _prev_frame_pressed(self):
PLAYER().seek_delta(-1)
self.show_current_frame()
def _next_frame_pressed(self):
PLAYER().seek_delta(1)
self.show_current_frame()
def _layer_selection_changed(self, selection):
selected_row = self.layer_list.get_selected_row()
# we're listeneing to "changed" on treeview and get some events (text updated)
# when layer selection was not changed.
if selected_row == -1:
return
self._activate_layer(selected_row)
def active_layer_changed(self, layer_index):
global _titler_data
_titler_data.active_layer = _titler_data.layers[layer_index]
self._update_gui_with_active_layer_data()
_titler_data.active_layer.update_pango_layout()
def _activate_layer(self, layer_index):
global _titler_data
_titler_data.active_layer = _titler_data.layers[layer_index]
self._update_gui_with_active_layer_data()
_titler_data.active_layer.update_pango_layout()
self.view_editor.activate_layer(layer_index)
self.view_editor.active_layer.update_rect = True
self.view_editor.edit_area.queue_draw()
def _editor_layer_mouse_released(self):
p = self.view_editor.active_layer.edit_point_shape.edit_points[0]
self.block_updates = True
self.x_pos_spin.set_value(p.x)
self.y_pos_spin.set_value(p.y)
#self.rotation_spin = gtk.SpinButton(adj)
_titler_data.active_layer.x = p.x
_titler_data.active_layer.y = p.y
self.block_updates = False
def _text_changed(self, widget):
self._update_active_layout()
def _position_value_changed(self, widget):
# mouse release when layer is moved causes this method to be called,
# but we don't want to do any additinal updates here for that event
# This is only used when user presses arrows in position spins.
if self.block_updates:
return
_titler_data.active_layer.x = self.x_pos_spin.get_value()
_titler_data.active_layer.y = self.y_pos_spin.get_value()
self._update_editor_layer_pos()
self.view_editor.edit_area.queue_draw()
def _edit_value_changed(self, widget):
self._update_active_layout()
def _update_active_layout(self, fill_layers_data_if_needed=True):
if self.block_updates:
return
global _titler_data
buf = self.text_view.get_buffer()
text = buf.get_text(buf.get_start_iter(), buf.get_end_iter(), include_hidden_chars=True)
if text != _titler_data.active_layer.text:
update_layers_list = True
else:
update_layers_list = False
_titler_data.active_layer.text = text
family = self.font_families[self.font_select.get_active()]
_titler_data.active_layer.font_family = family.get_name()
_titler_data.active_layer.font_size = self.size_spin.get_value_as_int()
face = FACE_REGULAR
if self.bold_font.get_active() and self.italic_font.get_active():
face = FACE_BOLD_ITALIC
elif self.italic_font.get_active():
face = FACE_ITALIC
elif self.bold_font.get_active():
face = FACE_BOLD
_titler_data.active_layer.font_face = face
align = ALIGN_LEFT
if self.center_align.get_active():
align = ALIGN_CENTER
elif self.right_align.get_active():
align = ALIGN_RIGHT
_titler_data.active_layer.alignment = align
color = self.color_button.get_color()
r, g, b = utils.hex_to_rgb(color.to_string())
new_color = (r/65535.0, g/65535.0, b/65535.0, 1.0)
_titler_data.active_layer.color_rgba = new_color
self.view_editor.active_layer.update_rect = True
_titler_data.active_layer.update_pango_layout()
# We only wnat to update layer list data model when this called after user typing
if update_layers_list:
self.layer_list.fill_data_model()
self.view_editor.edit_area.queue_draw()
def _update_gui_with_active_layer_data(self):
# This a bit hackish, but works. Finding a method that blocks all
# gui events from being added to queue would be nice.
self.block_updates = True
layer = _titler_data.active_layer
self.text_view.get_buffer().set_text(layer.text)
r, g, b, a = layer.color_rgba
button_color = gtk.gdk.Color(red=r,
green=g,
blue=b)
self.color_button.set_color(button_color)
if FACE_REGULAR == layer.font_face:
self.bold_font.set_active(False)
self.italic_font.set_active(False)
elif FACE_BOLD == layer.font_face:
self.bold_font.set_active(True)
self.italic_font.set_active(False)
elif FACE_ITALIC == layer.font_face:
self.bold_font.set_active(False)
self.italic_font.set_active(True)
else:#FACE_BOLD_ITALIC
self.bold_font.set_active(True)
self.italic_font.set_active(True)
if layer.alignment == ALIGN_LEFT:
self.left_align.set_active(True)
elif layer.alignment == ALIGN_CENTER:
self.center_align.set_active(True)
else:#ALIGN_RIGHT
self.right_align.set_active(True)
self.size_spin.set_value(layer.font_size)
try:
combo_index = self.font_family_indexes_for_name[layer.font_family]
self.font_select.set_active(combo_index)
except:# if font family not found we'll use first. This happens e.g at start-up if "Times New Roman" not in system.
family = self.font_families[0]
layer.font_family = family.get_name()
self.font_select.set_active(0)
self.x_pos_spin.set_value(layer.x)
self.y_pos_spin.set_value(layer.y)
self.rotation_spin.set_value(layer.angle)
self.block_updates = False
# --------------------------------------------------------- layer/s representation
class PangoTextLayout:
"""
Object for drawing current active layer with Pango.
Pixel size of layer can only be obtained when cairo context is available
for drawing, so pixel size of layer is saved here.
"""
def __init__(self, layer):
self.load_layer_data(layer)
def load_layer_data(self, layer):
self.text = layer.text
self.font_desc = pango.FontDescription(layer.get_font_desc_str())
self.color_rgba = layer.color_rgba
self.alignment = self._get_pango_alignment_for_layer(layer)
self.pixel_size = layer.pixel_size
# called from vieweditor draw vieweditor-> editorlayer->here
def draw_layout(self, cr, x, y, rotation, xscale, yscale):
cr.save()
pango_context = pangocairo.CairoContext(cr)
layout = pango_context.create_layout()
layout.set_text(self.text)
layout.set_font_description(self.font_desc)
layout.set_alignment(self.alignment)
self.pixel_size = layout.get_pixel_size()
pango_context.set_source_rgba(*self.color_rgba)
pango_context.move_to(x, y)
pango_context.scale( xscale, yscale)
pango_context.rotate(rotation)
pango_context.update_layout(layout)
pango_context.show_layout(layout)
cr.restore()
def _get_pango_alignment_for_layer(self, layer):
if layer.alignment == ALIGN_LEFT:
return pango.ALIGN_LEFT
elif layer.alignment == ALIGN_CENTER:
return pango.ALIGN_CENTER
else:
return pango.ALIGN_RIGHT
class TextLayerListView(gtk.VBox):
def __init__(self, selection_changed_cb, layer_visible_toggled_cb):
gtk.VBox.__init__(self)
self.layer_icon = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "text_layer.png")
self.eye_icon = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "eye.png")
self.layer_visible_toggled_cb = layer_visible_toggled_cb
# Datamodel: str
self.storemodel = gtk.ListStore(gtk.gdk.Pixbuf, str, gtk.gdk.Pixbuf)
# Scroll container
self.scroll = gtk.ScrolledWindow()
self.scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
self.scroll.set_shadow_type(gtk.SHADOW_ETCHED_IN)
# View
self.treeview = gtk.TreeView(self.storemodel)
self.treeview.set_property("rules_hint", True)
self.treeview.set_headers_visible(False)
self.treeview.connect("button-press-event", self.button_press)
tree_sel = self.treeview.get_selection()
tree_sel.set_mode(gtk.SELECTION_SINGLE)
tree_sel.connect("changed", selection_changed_cb)
# Cell renderers
self.text_rend_1 = gtk.CellRendererText()
self.text_rend_1.set_property("ellipsize", pango.ELLIPSIZE_END)
self.text_rend_1.set_property("font", "Sans Bold 10")
self.text_rend_1.set_fixed_height_from_font(1)
self.icon_rend_1 = gtk.CellRendererPixbuf()
self.icon_rend_1.props.xpad = 6
self.icon_rend_1.set_fixed_size(40, 40)
self.icon_rend_2 = gtk.CellRendererPixbuf()
self.icon_rend_2.props.xpad = 2
self.icon_rend_2.set_fixed_size(20, 40)
# Column view
self.icon_col_1 = gtk.TreeViewColumn("layer_icon")
self.text_col_1 = gtk.TreeViewColumn("layer_text")
self.icon_col_2 = gtk.TreeViewColumn("eye_icon")
# Build column views
self.icon_col_1.set_expand(False)
self.icon_col_1.set_spacing(5)
self.icon_col_1.pack_start(self.icon_rend_1)
self.icon_col_1.add_attribute(self.icon_rend_1, 'pixbuf', 0)
self.text_col_1.set_expand(True)
self.text_col_1.set_spacing(5)
self.text_col_1.set_sizing(gtk.TREE_VIEW_COLUMN_GROW_ONLY)
self.text_col_1.set_min_width(150)
self.text_col_1.pack_start(self.text_rend_1)
self.text_col_1.add_attribute(self.text_rend_1, "text", 1)
self.icon_col_2.set_expand(False)
self.icon_col_2.set_spacing(5)
self.icon_col_2.pack_start(self.icon_rend_2)
self.icon_col_2.add_attribute(self.icon_rend_2, 'pixbuf', 2)
# Add column views to view
self.treeview.append_column(self.icon_col_1)
self.treeview.append_column(self.text_col_1)
self.treeview.append_column(self.icon_col_2)
# Build widget graph and display
self.scroll.add(self.treeview)
self.pack_start(self.scroll)
self.scroll.show_all()
def button_press(self, tree_view, event):
if self.icon_col_1.get_width() + self.text_col_1.get_width() < event.x:
path = self.treeview.get_path_at_pos(int(event.x), int(event.y))
if path != None:
self.layer_visible_toggled_cb(max(path[0]))
def get_selected_row(self):
model, rows = self.treeview.get_selection().get_selected_rows()
# When listening to "changed" this gets called too often for our needs (namely when user types),
# but "row-activated" would activate layer changes only with double clicks, do we'll send -1 when this
# is called and active layer is not actually changed.
try:
return max(rows)[0]
except:
return -1
def fill_data_model(self):
"""
Creates displayed data.
Displays icon, sequence name and sequence length
"""
self.storemodel.clear()
for layer in _titler_data.layers:
if layer.visible:
visible_icon = self.eye_icon
else:
visible_icon = None
row_data = [self.layer_icon, layer.text, visible_icon]
self.storemodel.append(row_data)
self.scroll.queue_draw()
class OpenFileThread(threading.Thread):
def __init__(self, filename, view_editor):
threading.Thread.__init__(self)
self.filename = filename
self.view_editor = view_editor
def run(self):
# This makes sure that the file has been written to disk
while(self.view_editor.write_out_layers == True):
time.sleep(0.1)
open_in_bin_thread = projectaction.AddMediaFilesThread([self.filename])
open_in_bin_thread.start()
| Python |
#
# This file marks module.
#
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module handles keyevents.
"""
import pygtk
pygtk.require('2.0');
import gtk
import audiowaveform
import clipeffectseditor
import compositeeditor
import compositormodes
import glassbuttons
import gui
import editevent
import editorstate
from editorstate import current_sequence
from editorstate import PLAYER
from editorstate import timeline_visible
import keyframeeditor
import medialog
import monitorevent
import mltrefhold
import tlineaction
import updater
import projectaction
# ------------------------------------- keyboard events
def key_down(widget, event):
"""
Global key press listener.
"""
# Handle ESCAPE
if event.keyval == gtk.keysyms.Escape:
if audiowaveform.waveform_thread != None:
audiowaveform.waveform_thread.abort_rendering()
return True
else:
if editorstate.current_is_move_mode() == False:
editevent.set_default_edit_mode()
return True
# If timeline widgets are in focus timeline keyevents are available
if _timeline_has_focus():
was_handled = _handle_tline_key_event(event)
if was_handled:
# Stop widget focus from travelling if arrow key pressed for next frame
# by stopping signal
gui.editor_window.window.emit_stop_by_name("key_press_event")
return was_handled
# Insert shortcut keys need more focus then timeline shortcuts.
# these may already have been handled in timeline focus events
was_handled = _handle_extended_tline_focus_events(event)
if was_handled:
# Stop event handling here
return True
was_handled = _handle_geometry_editor_arrow_keys(event)
if was_handled:
# Stop widget focus from travelling if arrow key pressed
gui.editor_window.window.emit_stop_by_name("key_press_event")
return True
# Pressing timeline button obivously leaves user expecting
# to have focus in timeline
if gui.sequence_editor_b.has_focus():
_handle_tline_key_event(event)
# Stop event handling here
return True
# Clip button or posbar focus with clip displayed leaves playback keyshortcuts available
if (gui.clip_editor_b.has_focus()
or (gui.pos_bar.widget.is_focus() and (not timeline_visible()))):
_handle_clip_key_event(event)
# Stop event handling here
return True
# Handle non-timeline delete
if event.keyval == gtk.keysyms.Delete:
return _handle_delete()
# Home
if event.keyval == gtk.keysyms.Home:
if PLAYER().is_playing():
monitorevent.stop_pressed()
PLAYER().seek_frame(0)
return True
# Select all with CTRL + A in media panel
if event.keyval == gtk.keysyms.a:
if (event.state & gtk.gdk.CONTROL_MASK):
if gui.media_list_view.widget.has_focus() or gui.media_list_view.widget.get_focus_child() != None:
gui.media_list_view.select_all()
return True
#debug
if event.keyval == gtk.keysyms.F11:
if (event.state & gtk.gdk.CONTROL_MASK):
mltrefhold.print_objects()
return True
#debug
if event.keyval == gtk.keysyms.F12:
if (event.state & gtk.gdk.CONTROL_MASK):
mltrefhold.print_and_clear()
return True
# Key event was not handled here.
return False
def _timeline_has_focus():
if(gui.tline_canvas.widget.is_focus()
or gui.tline_column.widget.is_focus()
or gui.editor_window.modes_selector.widget.is_focus()
or (gui.pos_bar.widget.is_focus() and timeline_visible())
or gui.tline_scale.widget.is_focus()
or glassbuttons.focus_group_has_focus(glassbuttons.DEFAULT_FOCUS_GROUP)):
return True
return False
def _handle_tline_key_event(event):
"""
This is called when timeline widgets have focus and key is pressed.
Returns True for handled key presses to stop those
keyevents from going forward.
"""
# I
if event.keyval == gtk.keysyms.i:
if (event.state & gtk.gdk.MOD1_MASK):
monitorevent.to_mark_in_pressed()
return True
monitorevent.mark_in_pressed()
return True
if event.keyval == gtk.keysyms.I:
if (event.state & gtk.gdk.MOD1_MASK):
monitorevent.to_mark_in_pressed()
return True
monitorevent.to_mark_in_pressed()
return True
# O
if event.keyval == gtk.keysyms.o:
if (event.state & gtk.gdk.MOD1_MASK):
monitorevent.to_mark_out_pressed()
return True
monitorevent.mark_out_pressed()
return True
if event.keyval == gtk.keysyms.O:
if (event.state & gtk.gdk.MOD1_MASK):
monitorevent.to_mark_out_pressed()
return True
monitorevent.to_mark_out_pressed()
return True
# SPACE
if event.keyval == gtk.keysyms.space:
if PLAYER().is_playing():
monitorevent.stop_pressed()
else:
monitorevent.play_pressed()
return True
# TAB
if event.keyval == gtk.keysyms.Tab:
updater.switch_monitor_display()
return True
# M
if event.keyval == gtk.keysyms.m:
tlineaction.add_marker()
return True
# Number edit mode changes
if event.keyval == gtk.keysyms._1:
gui.editor_window.handle_insert_move_mode_button_press()
gui.editor_window.set_mode_selector_to_mode()
return True
if event.keyval == gtk.keysyms._2:
gui.editor_window.handle_over_move_mode_button_press()
gui.editor_window.set_mode_selector_to_mode()
return True
if event.keyval == gtk.keysyms._3:
gui.editor_window.handle_one_roll_mode_button_press()
gui.editor_window.set_mode_selector_to_mode()
return True
if event.keyval == gtk.keysyms._4:
gui.editor_window.handle_two_roll_mode_button_press()
gui.editor_window.set_mode_selector_to_mode()
return True
if event.keyval == gtk.keysyms._5:
gui.editor_window.handle_slide_mode_button_press()
gui.editor_window.set_mode_selector_to_mode()
return True
if event.keyval == gtk.keysyms._6:
gui.editor_window.handle_multi_mode_button_press()
gui.editor_window.set_mode_selector_to_mode()
return True
# X
if event.keyval == gtk.keysyms.x:
tlineaction.cut_pressed()
return True
# G
if event.keyval == gtk.keysyms.g:
medialog.log_range_clicked()
return True
# Key bindings for MOVE MODES and _NO_EDIT modes
if editorstate.current_is_move_mode() or editorstate.current_is_active_trim_mode() == False:
# UP ARROW, next cut
if event.keyval == gtk.keysyms.Up:
if editorstate.timeline_visible():
tline_frame = PLAYER().tracktor_producer.frame()
frame = current_sequence().find_next_cut_frame(tline_frame)
if frame != -1:
PLAYER().seek_frame(frame)
return True
else:
monitorevent.up_arrow_seek_on_monitor_clip()
# DOWN ARROW, prev cut
if event.keyval == gtk.keysyms.Down:
if editorstate.timeline_visible():
tline_frame = PLAYER().tracktor_producer.frame()
frame = current_sequence().find_prev_cut_frame(tline_frame)
if frame != -1:
PLAYER().seek_frame(frame)
return True
else:
monitorevent.down_arrow_seek_on_monitor_clip()
return True
# LEFT ARROW, prev frame
if event.keyval == gtk.keysyms.Left:
PLAYER().seek_delta(-1)
return True
# RIGHT ARROW, next frame
if event.keyval == gtk.keysyms.Right:
PLAYER().seek_delta(1)
return True
# T
if event.keyval == gtk.keysyms.t:
tlineaction.three_point_overwrite_pressed()
return True
# Y
if event.keyval == gtk.keysyms.y:
if not (event.state & gtk.gdk.CONTROL_MASK):
tlineaction.insert_button_pressed()
return True
# U
if event.keyval == gtk.keysyms.u:
tlineaction.append_button_pressed()
return True
# J
if event.keyval == gtk.keysyms.j:
monitorevent.j_pressed()
return True
# K
if event.keyval == gtk.keysyms.k:
monitorevent.k_pressed()
return True
# L
if event.keyval == gtk.keysyms.l:
if (event.state & gtk.gdk.CONTROL_MASK):
medialog.log_range_clicked()
else:
monitorevent.l_pressed()
return True
# CTRL+C
if event.keyval == gtk.keysyms.c:
if (event.state & gtk.gdk.CONTROL_MASK):
tlineaction.do_timeline_objects_copy()
return True
# CTRL+V
if event.keyval == gtk.keysyms.v:
if (event.state & gtk.gdk.CONTROL_MASK):
tlineaction.do_timeline_objects_paste()
return True
# DELETE
if event.keyval == gtk.keysyms.Delete:
# Clip selection and compositor selection are mutually exclusive,
# so max one one these will actually delete something
tlineaction.splice_out_button_pressed()
compositormodes.delete_current_selection()
# HOME
if event.keyval == gtk.keysyms.Home:
if PLAYER().is_playing():
monitorevent.stop_pressed()
PLAYER().seek_frame(0)
return True
else:
# HOME
if event.keyval == gtk.keysyms.Home:
if PLAYER().is_playing():
monitorevent.stop_pressed()
gui.editor_window.handle_insert_move_mode_button_press()
gui.editor_window.set_mode_selector_to_mode()
PLAYER().seek_frame(0)
return True
return False
def _handle_extended_tline_focus_events(event):
# This was added to fix to a bug long time ago but the rationale for "extended_tline_focus_events" has been forgotten, but probably still exists
if not(_timeline_has_focus() or
gui.pos_bar.widget.is_focus() or
gui.sequence_editor_b.has_focus() or
gui.clip_editor_b.has_focus()):
return False
# T
if event.keyval == gtk.keysyms.t:
tlineaction.three_point_overwrite_pressed()
return True
# Y
if event.keyval == gtk.keysyms.y:
if not (event.state & gtk.gdk.CONTROL_MASK):
tlineaction.insert_button_pressed()
return True
# U
if event.keyval == gtk.keysyms.u:
tlineaction.append_button_pressed()
return True
# J
if event.keyval == gtk.keysyms.j:
monitorevent.j_pressed()
return True
# K
if event.keyval == gtk.keysyms.k:
monitorevent.k_pressed()
return True
# L
if event.keyval == gtk.keysyms.l:
if (event.state & gtk.gdk.CONTROL_MASK):
medialog.log_range_clicked()
else:
monitorevent.l_pressed()
return True
# TAB
if event.keyval == gtk.keysyms.Tab:
updater.switch_monitor_display()
return True
# G
if event.keyval == gtk.keysyms.g:
medialog.log_range_clicked()
return True
# Number edit mode changes
if event.keyval == gtk.keysyms._1:
gui.editor_window.handle_insert_move_mode_button_press()
gui.editor_window.set_mode_selector_to_mode()
return True
if event.keyval == gtk.keysyms._2:
gui.editor_window.handle_over_move_mode_button_press()
gui.editor_window.set_mode_selector_to_mode()
return True
if event.keyval == gtk.keysyms._3:
gui.editor_window.handle_one_roll_mode_button_press()
gui.editor_window.set_mode_selector_to_mode()
return True
if event.keyval == gtk.keysyms._4:
gui.editor_window.handle_two_roll_mode_button_press()
gui.editor_window.set_mode_selector_to_mode()
return True
if event.keyval == gtk.keysyms._5:
gui.editor_window.handle_slide_mode_button_press()
gui.editor_window.set_mode_selector_to_mode()
return True
if event.keyval == gtk.keysyms._6:
gui.editor_window.handle_multi_mode_button_press()
gui.editor_window.set_mode_selector_to_mode()
return True
return False
def _handle_clip_key_event(event):
# Key bindings for MOVE MODES
if editorstate.current_is_move_mode():
# LEFT ARROW, prev frame
if event.keyval == gtk.keysyms.Left:
PLAYER().seek_delta(-1)
return
# RIGHT ARROW, next frame
if event.keyval == gtk.keysyms.Right:
PLAYER().seek_delta(1)
return
# UP ARROW
if event.keyval == gtk.keysyms.Up:
if editorstate.timeline_visible():
tline_frame = PLAYER().tracktor_producer.frame()
frame = current_sequence().find_next_cut_frame(tline_frame)
if frame != -1:
PLAYER().seek_frame(frame)
return True
else:
monitorevent.up_arrow_seek_on_monitor_clip()
return True
# DOWN ARROW, prev cut
if event.keyval == gtk.keysyms.Down:
if editorstate.timeline_visible():
tline_frame = PLAYER().tracktor_producer.frame()
frame = current_sequence().find_prev_cut_frame(tline_frame)
if frame != -1:
PLAYER().seek_frame(frame)
return True
else:
monitorevent.down_arrow_seek_on_monitor_clip()
return True
# SPACE
if event.keyval == gtk.keysyms.space:
if PLAYER().is_playing():
monitorevent.stop_pressed()
else:
monitorevent.play_pressed()
# I
if event.keyval == gtk.keysyms.i:
if (event.state & gtk.gdk.MOD1_MASK):
monitorevent.to_mark_in_pressed()
return True
monitorevent.mark_in_pressed()
return True
if event.keyval == gtk.keysyms.I:
if (event.state & gtk.gdk.MOD1_MASK):
monitorevent.to_mark_in_pressed()
return True
monitorevent.to_mark_in_pressed()
return True
# O
if event.keyval == gtk.keysyms.o:
if (event.state & gtk.gdk.MOD1_MASK):
monitorevent.to_mark_out_pressed()
return True
monitorevent.mark_out_pressed()
return True
if event.keyval == gtk.keysyms.O:
if (event.state & gtk.gdk.MOD1_MASK):
monitorevent.to_mark_out_pressed()
return True
monitorevent.to_mark_out_pressed()
return True
def _handle_delete():
# Delete media file
if gui.media_list_view.widget.get_focus_child() != None:
projectaction.delete_media_files()
return True
# Delete bin
if gui.bin_list_view.get_focus_child() != None:
if gui.bin_list_view.text_rend_1.get_property("editing") == True:
return False
projectaction.delete_selected_bin()
return True
# Delete sequence
if gui.sequence_list_view.get_focus_child() != None:
if gui.sequence_list_view.text_rend_1.get_property("editing") == True:
return False
projectaction.delete_selected_sequence()
return True
# Delete effect
if gui.effect_stack_list_view.get_focus_child() != None:
clipeffectseditor.delete_effect_pressed()
return True
# Delete media log event
if gui.editor_window.media_log_events_list_view.get_focus_child() != None:
medialog.delete_selected()
return True
focus_editor = _get_focus_keyframe_editor(compositeeditor.keyframe_editor_widgets)
if focus_editor != None:
focus_editor.delete_pressed()
return True
focus_editor = _get_focus_keyframe_editor(clipeffectseditor.keyframe_editor_widgets)
if focus_editor != None:
focus_editor.delete_pressed()
return True
return False
def _handle_geometry_editor_arrow_keys(event):
if compositeeditor.keyframe_editor_widgets != None:
for kfeditor in compositeeditor.keyframe_editor_widgets:
if kfeditor.get_focus_child() != None:
if kfeditor.__class__ == keyframeeditor.GeometryEditor:
if ((event.keyval == gtk.keysyms.Left)
or (event.keyval == gtk.keysyms.Right)
or (event.keyval == gtk.keysyms.Up)
or (event.keyval == gtk.keysyms.Down)):
kfeditor.arrow_edit(event.keyval)
return True
return False
def _get_focus_keyframe_editor(keyframe_editor_widgets):
if keyframe_editor_widgets == None:
return None
for kfeditor in keyframe_editor_widgets:
if kfeditor.get_focus_child() != None:
return kfeditor
return None
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2014 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
import copy
CR_BASIS = [[-0.5, 1.5, -1.5, 0.5],
[ 1.0, -2.5, 2.0, -0.5],
[-0.5, 0.0, 0.5, 0.0],
[ 0.0, 1.0, 0.0, 0.0]]
RED = 0
GREEN = 1
BLUE = 2
SHADOWS = 0
MIDTONES = 1
HIGHLIGHTS = 2
LINEAR_LUT_256 = []
for i in range(0, 256):
LINEAR_LUT_256.append(i)
MULT_TABLE_256 = []
for i in range(0, 256):
MULT_TABLE_256.append(0.0)
class CurvePoint:
def __init__(self, x, y):
self.x = x
self.y = y
class CRCurve:
def __init__(self):
self.CURVES_NUM_POINTS = 17;#this should be enough.
self.X = 0
self.Y = 1
self.points = []
self.curve = []
self.curve_reset()
def curve_reset(self):
self.curve = []
for i in range(0, 256):
self.curve.append(i)
self.points = []
self.set_curve_point(CurvePoint(0, 0))
self.set_curve_point(CurvePoint(255, 255))
def set_curve_point(self, new_point):
if len(self.points) + 1 > self.CURVES_NUM_POINTS:
return
for i, p in reversed(list(enumerate(self.points))):
if p.x == new_point.x:
self.points.pop(i)
self.points.append(new_point)
self.points = sorted(self.points, key=lambda point: point.x)
def set_points_from_str(self, points_str):
points = []
tokens = points_str.split(";")
for t in tokens:
x, y = t.split("/")
point = CurvePoint(int(x), int(y))
points.append(point)
self.points = sorted(points, key=lambda point: point.x)
self.calculate_curve()
def get_points_string(self):
l = []
for i in range(0, len(self.points)):
p = self.points[i]
l.append(str(p.x))
l.append("/")
l.append(str(p.y))
l.append(";")
return ''.join(l).rstrip(";")
def get_curve(self, calculate_first):
if calculate_first:
self.calculate_curve()
return self.curve
def remove_range(self, p1, p2):
if( p1 > p2 ):
p1,p2 = p2,p1
for x in range(int(p1), int(p2) + 1):
self.remove_curve_point(CurvePoint(x, -1))
def remove_curve_point(self, p):
if len(self.points) < 2:
return
for i, curve_p in list(enumerate(self.points)):
if p.x == curve_p.x:
self.points.pop(i)
def calculate_curve(self):
# Initialize boundary curve points
if len(self.points) != 0:
p = self.points[0]
for i in range(0, p.x):
self.curve[i] = p.y
p = self.points[-1]
for i in range(p.x, 256):
self.curve[i] = p.y
# Plot curves
for i in range(0, len(self.points) - 1): # int i = 0; i < points.size() - 1; i++)
if i == 0:
p1 = self.points[0] #points.elementAt( i );
else:
p1 = self.points[i - 1]
p2 = self.points[i]
p3 = self.points[i + 1]
if i == len(self.points) - 2:
p4 = self.points[len(self.points) - 2]# points.elementAt( points.size() - 1 );
else:
p4 = self.points[i + 2]
self.plot_curve( p1, p2, p3, p4)
# ensure that the control points are used exactly.
for i in range(0, len(self.points)):#( int i = 0; i < points.size(); i++)
x = self.points[i].x
y = self.points[i].y
self.curve[x] = y
def get4x4list(self):
return [[0.0,0.0,0.0,0.0],
[0.0,0.0,0.0,0.0],
[0.0,0.0,0.0,0.0],
[0.0,0.0,0.0,0.0]]
def plot_curve (self, p1, p2, p3, p4):
geometry = self.get4x4list()
tmp1 = self.get4x4list()
tmp2 = self.get4x4list()
deltas = self.get4x4list()
N = 1000
# construct the geometry matrix from the segment
for i in range(0, 4):#( int i = 0; i < 4; i++)
geometry[i][2] = 0
geometry[i][3] = 0
# Get points X and Y
X = self.X
Y = self.Y
geometry[0][X] = float(p1.x)
geometry[1][X] = float(p2.x)
geometry[2][X] = float(p3.x)
geometry[3][X] = float(p4.x)
geometry[0][Y] = float(p1.y)
geometry[1][Y] = float(p2.y)
geometry[2][Y] = float(p3.y)
geometry[3][Y] = float(p4.y)
# subdivide the curve N times (N = 1000 )
# N can be adjusted to give a finer or coarser curve
d = 1.0 / N
d2 = d * d
d3 = d * d * d
# construct a temporary matrix for determining the forward differencing deltas
tmp2[0][0] = 0.0
tmp2[0][1] = 0.0
tmp2[0][2] = 0.0
tmp2[0][3] = 1.0
tmp2[1][0] = d3
tmp2[1][1] = d2
tmp2[1][2] = d
tmp2[1][3] = 0.0
tmp2[2][0] = 6.0 * d3
tmp2[2][1] = 2.0 * d2
tmp2[2][2] = 0.0
tmp2[2][3] = 0.0
tmp2[3][0] = 6.0 * d3
tmp2[3][1] = 0.0
tmp2[3][2] = 0.0
tmp2[3][3] = 0.0
# compose the basis and geometry matrices
self.curves_CR_compose(CR_BASIS, geometry, tmp1)
# compose the above results to get the deltas matrix
self.curves_CR_compose(tmp2, tmp1, deltas)
# extract the x deltas
x = deltas[0][0]
dx = deltas[1][0]
dx2 = deltas[2][0]
dx3 = deltas[3][0]
# extract the y deltas
y = deltas[0][1]
dy = deltas[1][1]
dy2 = deltas[2][1]
dy3 = deltas[3][1]
lastx = clamp(round(x))
lasty = clamp(round(y))
self.curve[lastx] = lasty
# Loop over the curve and build LUT
for i in range(0, N):
# increment the x values
x += dx
dx += dx2
dx2 += dx3
# increment the y values
y += dy
dy += dy2
dy2 += dy3
newx = clamp(round( x ))
newy = clamp(round( y ))
# if this point is different than the last one...then draw it
if (( lastx != newx ) or ( lasty != newy)):
self.curve[ newx ] = newy
lastx = newx;
lasty = newy;
# Fills ab using a and b
def curves_CR_compose(self, a, b, ab):
for i in range(0, 4):
for j in range(0, 4):
ab[i][j] = (a[i][0] * b[0][j] + \
a[i][1] * b[1][j] + \
a[i][2] * b[2][j] + \
a[i][3] * b[3][j])
class CatmullRomFilter:
def __init__(self, editable_properties):
# These properties hold the values that are writtenout to MLT to do the filtering
self.r_table_prop = filter(lambda ep: ep.name == "R_table", editable_properties)[0]
self.g_table_prop = filter(lambda ep: ep.name == "G_table", editable_properties)[0]
self.b_table_prop = filter(lambda ep: ep.name == "B_table", editable_properties)[0]
# These properties hold points lists which define cr curves. They are persistent but are not
# written out to MLT
self.r_points_prop = filter(lambda ep: ep.name == "r_curve", editable_properties)[0]
self.g_points_prop = filter(lambda ep: ep.name == "g_curve", editable_properties)[0]
self.b_points_prop = filter(lambda ep: ep.name == "b_curve", editable_properties)[0]
self.value_points_prop = filter(lambda ep: ep.name == "value_curve", editable_properties)[0]
# These are objects that generate lut tables from points lists
self.r_cr_curve = CRCurve()
self.r_cr_curve.set_points_from_str(self.r_points_prop.value)
self.g_cr_curve = CRCurve()
self.g_cr_curve.set_points_from_str(self.g_points_prop.value)
self.b_cr_curve = CRCurve()
self.b_cr_curve.set_points_from_str(self.b_points_prop.value)
self.value_cr_curve = CRCurve()
self.value_cr_curve.set_points_from_str(self.value_points_prop.value)
def update_table_property_values(self):
# R, G, B LUT table are created with input from value gamma curve to all of them
gamma = self.value_cr_curve.curve
r_table = self.apply_gamma_to_channel(gamma, self.r_cr_curve.curve)
g_table = self.apply_gamma_to_channel(gamma, self.g_cr_curve.curve)
b_table = self.apply_gamma_to_channel(gamma, self.b_cr_curve.curve)
self.r_table_prop.write_out_table(r_table)
self.g_table_prop.write_out_table(g_table)
self.b_table_prop.write_out_table(b_table)
def apply_gamma_to_channel(self, gamma, channel_pregamma):
lut = []
# Value for table index 0
try:
val = gamma[0] * (gamma[0] / channel_pregamma[0])
except:
val = gamma[0]
lut.append(clamp(round(val)))
# Value for table index 1 - 255
for i in range(1, 256):
gmul = float(gamma[i]) / float(LINEAR_LUT_256[i])
val = gmul * float(channel_pregamma[i])
lut.append(clamp(round(val)))
return lut
class ColorGradeBandCorrection:
def __init__(self):
self.r_mult = 0.0
self.g_mult = 0.0
self.b_mult = 0.0
self.mask_curve = CRCurve()
self.r_mult_table = copy.deepcopy(MULT_TABLE_256)
self.g_mult_table = copy.deepcopy(MULT_TABLE_256)
self.b_mult_table = copy.deepcopy(MULT_TABLE_256)
self.r_correction_look_up = copy.deepcopy(LINEAR_LUT_256)
self.g_correction_look_up = copy.deepcopy(LINEAR_LUT_256)
self.b_correction_look_up = copy.deepcopy(LINEAR_LUT_256)
def set_hue_and_saturation(self, hue, saturation):
# Convert saved and editor hue, saturation ranges to one used
# to generate look-up tables
saturation = (saturation - 0.5) * 2.0
# Negative saturation means addding complementary color
if saturation < 0.0:
saturation = abs(saturation)
hue = hue + 0.5
if hue > 1.0:
hue = hue - 1.0
# Get r, g, b multipliers
r, g, b = get_RGB_for_angle_saturation_and_value(hue * 360, saturation, 0.5)
self.r_mult = (r - 0.5) / 0.5
self.g_mult = (g - 0.5) / 0.5
self.b_mult = (b - 0.5) / 0.5
#print r, g, b
#print self.r_mult, self.g_mult, self.b_mult
def set_mask_points(self, points_str, range_in, range_out):
self.mask_curve.set_points_from_str(points_str)
# overwrite parts not in range with value 128
for i in range(0, range_in):
self.mask_curve.curve[i] = 128
for i in range(range_out, 256):
self.mask_curve.curve[i] = 128
#self.print_table(self.mask_curve.curve)
def update_correction(self):
for i in range(0, 256):
self.r_mult_table[i] = (float(self.mask_curve.curve[i] - 128) / 128.0) * self.r_mult
self.g_mult_table[i] = (float(self.mask_curve.curve[i] - 128) / 128.0) * self.g_mult
self.b_mult_table[i] = (float(self.mask_curve.curve[i] - 128) / 128.0) * self.b_mult
#self.print_table(self.r_mult_table)
CORRECTION_STRENGTH_MULT = 100.0
for i in range(0, 256):
self.r_correction_look_up[i] = int(self.r_mult_table[i] * CORRECTION_STRENGTH_MULT) #- LINEAR_LUT_256[i]
self.g_correction_look_up[i] = int(self.g_mult_table[i] * CORRECTION_STRENGTH_MULT) #- LINEAR_LUT_256[i]
self.b_correction_look_up[i] = int(self.b_mult_table[i] * CORRECTION_STRENGTH_MULT) #- LINEAR_LUT_256[i]
#self.print_table(self.r_correction_look_up)
def print_table(self, table):
for i in range(0, len(table)):
print str(i) + ":" + str(table[i])
class ColorGradeFilter:
def __init__(self, editable_properties):
# These properties hold the values that are writtenout to MLT to do the filtering
self.r_table_prop = filter(lambda ep: ep.name == "R_table", editable_properties)[0]
self.g_table_prop = filter(lambda ep: ep.name == "G_table", editable_properties)[0]
self.b_table_prop = filter(lambda ep: ep.name == "B_table", editable_properties)[0]
self.r_lookup = [0] * 256
self.g_lookup = [0] * 256
self.b_lookup = [0] * 256
self.shadow_band = ColorGradeBandCorrection()
self.shadow_band.set_mask_points("0/128;20/180;45/200;128/146;255/128", 0, 255)
self.mid_band = ColorGradeBandCorrection()
self.mid_band.set_mask_points("0/128;80/155;128/200;170/155;255/128", 0, 255)
self.hi_band = ColorGradeBandCorrection()
self.hi_band.set_mask_points("0/128;128/128;220/200;255/128", 0, 255)
def update_all_corrections(self):
self.shadow_band.update_correction()
self.mid_band.update_correction()
self.hi_band.update_correction()
def update_rgb_lookups(self):
for i in range(0, 256):
self.r_lookup[i] = clamp(i + self.shadow_band.r_correction_look_up[i] + \
self.mid_band.r_correction_look_up[i] + \
self.hi_band.r_correction_look_up[i])
self.g_lookup[i] = clamp(i + self.shadow_band.g_correction_look_up[i] + \
self.mid_band.g_correction_look_up[i] + \
self.hi_band.g_correction_look_up[i])
self.b_lookup[i] = clamp(i + self.shadow_band.b_correction_look_up[i] + \
self.mid_band.b_correction_look_up[i] + \
self.hi_band.b_correction_look_up[i])
def write_out_tables(self):
self.r_table_prop.write_out_table(self.r_lookup)
self.g_table_prop.write_out_table(self.g_lookup)
self.b_table_prop.write_out_table(self.b_lookup)
def get_RGB_for_angle(angle):
hsl = get_HSL(angle, 1.0, 0.5)
return hsl_to_rgb(hsl)
def get_RGB_for_angle_saturation_and_value(angle, saturation, value):
hsl = get_HSL(angle,saturation, value)
return hsl_to_rgb(hsl)
def get_HSL(h, s, l):
h = h / 360.0
return (h, s, l)
def hsl_to_rgb(hsl):
h, s, l = hsl
if s == 0.0:
# achromatic case
r = l
g = l
b = l
else:
if l <= 0.5:
m2 = l * (1.0 + s)
else:
m2 = l + s - l * s
m1 = 2.0 * l - m2
r = hsl_value( m1, m2, h * 6.0 + 2.0 )
g = hsl_value( m1, m2, h * 6.0 )
b = hsl_value( m1, m2, h * 6.0 - 2.0 )
return (r, g, b)
def hsl_value(n1, n2, hue):
if hue > 6.0:
hue -= 6.0
elif hue < 0.0:
hue += 6.0
if hue < 1.0:
val = n1 + (n2 - n1) * hue
elif hue < 3.0:
val = n2
elif hue < 4.0:
val = n1 + (n2 - n1) * (4.0 - hue)
else:
val = n1
return val
def SQR(v):
return v * v
def clamp(val):
if val > 255:
return 255
if val < 0:
return 0
return int(val)
"""
class ColorCorrectorFilter:
SHADOWS_DIST_MULT = 0.75
MID_DIST_MULT = 125.0
HI_DIST_MULT = 0.5
LIFT_CONV = 0.5 / 127.0
GAIN_CONV = 0.5 / 127.0
GAMMA_CONV = 0.5 / 127.0
def __init__(self, editable_properties):
self.r_table_prop = filter(lambda ep: ep.name == "R_table", editable_properties)[0]
self.g_table_prop = filter(lambda ep: ep.name == "G_table", editable_properties)[0]
self.b_table_prop = filter(lambda ep: ep.name == "B_table", editable_properties)[0]
self.r_lookup = [0] * 256
self.g_lookup = [0] * 256
self.b_lookup = [0] * 256
self.cyan_red = [0] * 3
self.magenta_green = [0] * 3
self.yellow_blue = [0] * 3
self.highlights_add = [0] * 256
self.shadows_sub = [0] * 256
self.midtones_add = [0] * 256
self.midtones_sub = [0] * 256
self.shadows_add = [0] * 256
self.highlights_sub = [0] * 256
self._fill_add_sub_tables()
self.create_lookup_tables()
def _fill_add_sub_tables(self):
for i in range(0, 256):
self.highlights_add[i] = 1.075 - 1.0 / (float(i) / 16.0 + 1.0)
self.shadows_sub[255 - i] = 1.075 - 1.0 / (float(i) / 16.0 + 1.0)
self.midtones_add[i] = 0.667 * (1.0 - SQR((float(i) - 127.0) / 127.0))
self.midtones_sub[i] = 0.667 * (1.0 - SQR((float(i) - 127.0) / 127.0))
self.shadows_add[i] = 0.667 * (1.0 - SQR((float(i) - 127.0) / 127.0))
self.highlights_sub[i] = 0.667 * (1.0 - SQR((float(i) - 127.0) / 127.0))
def set_shadows_correction(self, angle, distance):
r, g, b = get_RGB_for_angle(angle)
distance = distance * ColorCorrectorFilter.SHADOWS_DIST_MULT
max_color = RED
if g >= r and g >= b:
max_color = GREEN
if b >= r and b >= g:
maxColor = BLUE
val_R = 0.0
val_G = 0.0
val_B = 0.0
dR = 0.0
dG = 0.0
dB = 0.0
if max_color == RED:
dG = r - g
dB = r - b
val_G = -100.0 * distance * dG
val_B = -100.0 * distance * dB
if max_color == GREEN:
dR = g - r
dB = g - b
val_B = -100.0 * distance * dB
val_R = -100.0 * distance * dR
if max_color == BLUE:
dR = b - r
dG = b - g
val_G = -100.0 * distance * dG;
val_R = -100.0 * distance * dR;
self.cyan_red[SHADOWS] = val_R
self.magenta_green[SHADOWS] = val_G
self.yellow_blue[SHADOWS] = val_B
def set_midtone_correction(self, angle, distance):
rng = distance * ColorCorrectorFilter.MID_DIST_MULT #float range = distance * MID_DIST_MULT;
floor = -(rng / 2)
r, g, b = get_RGB_for_angle(angle) #GiottoRGB rgb = getRGB( angle );
val_R = floor + rng * r
val_G = floor + rng * g
val_B = floor + rng * b
self.cyan_red[MIDTONES] = val_R
self.magenta_green[MIDTONES] = val_G
self.yellow_blue[MIDTONES] = val_B
def set_high_ligh_correction(self, angle, distance):
r, g, b = get_RGB_for_angle(angle)
distance = distance * ColorCorrectorFilter.HI_DIST_MULT
min_color = RED
if g <= r and g <= b:
min_color = GREEN
if b <= r and b <= g:
minColor = BLUE
val_R = 0.0
val_G = 0.0
val_B = 0.0
dR = 0.0
dG = 0.0
dB = 0.0
if min_color == RED:
dG = g - r
dB = b - r
val_G = 100.0 * distance * dG
val_B = 100.0 * distance * dB
val_R = 0.0
if min_color == GREEN:
dR = r - g
dB = b - g
val_G = 0.0
val_B = 100.0 * distance * dB
val_R = 100.0 * distance * dR
if min_color == BLUE:
dR = r - b
dG = b - b
val_G = 100.0 * distance * dG
val_B = 0
val_R = 100.0 * distance * dR
self.cyan_red[HIGHLIGHTS] = val_R
self.magenta_green[HIGHLIGHTS] = val_G
self.yellow_blue[HIGHLIGHTS] = val_B
def create_lookup_tables(self):
cyan_red_transfer = [[0] * 3 for i in range(256)] # float[3][256];
magenta_green_transfer = [[0] * 3 for i in range(256)]
yellow_blue_transfer = [[0] * 3 for i in range(256)]
cyan_red_transfer[SHADOWS] = self.shadows_add if self.cyan_red[ SHADOWS ] > 0 else self.shadows_sub
cyan_red_transfer[MIDTONES] = self.midtones_add if self.cyan_red[ MIDTONES ] > 0 else self.midtones_sub
cyan_red_transfer[HIGHLIGHTS] = self.highlights_add if self.cyan_red[ HIGHLIGHTS ] > 0 else self.highlights_sub
magenta_green_transfer[SHADOWS] = self.shadows_add if self.magenta_green[SHADOWS] > 0 else self.shadows_sub
magenta_green_transfer[MIDTONES] = self.midtones_add if self.magenta_green[MIDTONES] > 0 else self.midtones_sub
magenta_green_transfer[HIGHLIGHTS] = self.highlights_add if self.magenta_green[HIGHLIGHTS] > 0 else self.highlights_sub
yellow_blue_transfer[SHADOWS] = self.shadows_add if self.yellow_blue[SHADOWS] > 0 else self.shadows_sub
yellow_blue_transfer[MIDTONES] = self.midtones_add if self.yellow_blue[MIDTONES] > 0 else self.midtones_sub
yellow_blue_transfer[HIGHLIGHTS] = self.highlights_add if self.yellow_blue[HIGHLIGHTS] > 0 else self.highlights_sub
for i in range(0, 256):
r_n = i
g_n = i
b_n = i
r_n +=int(self.cyan_red[SHADOWS] * cyan_red_transfer[SHADOWS][r_n])
r_n = clamp(r_n)
r_n += int(self.cyan_red[MIDTONES] * cyan_red_transfer[MIDTONES][r_n])
r_n = clamp(r_n)
r_n += int(self.cyan_red[HIGHLIGHTS] * cyan_red_transfer[HIGHLIGHTS][r_n])
r_n = clamp(r_n)
g_n += int(self.magenta_green[SHADOWS] * magenta_green_transfer[SHADOWS][g_n])
g_n = clamp(g_n)
g_n += int(self.magenta_green[MIDTONES] * magenta_green_transfer[MIDTONES][g_n])
g_n = clamp(g_n)
g_n += int(self.magenta_green[HIGHLIGHTS] * magenta_green_transfer[HIGHLIGHTS][g_n])
g_n = clamp(g_n)
b_n += int(self.yellow_blue[SHADOWS] * yellow_blue_transfer[SHADOWS][b_n])
b_n = clamp(b_n)
b_n += int(self.yellow_blue[MIDTONES] * yellow_blue_transfer[MIDTONES][b_n])
b_n = clamp(b_n)
b_n += int(self.yellow_blue[HIGHLIGHTS] * yellow_blue_transfer[HIGHLIGHTS][b_n])
b_n = clamp(b_n)
self.r_lookup[i] = r_n
self.g_lookup[i] = g_n
self.b_lookup[i] = b_n
def write_out_tables(self):
self.r_table_prop.write_out_table(self.r_lookup)
self.g_table_prop.write_out_table(self.g_lookup)
self.b_table_prop.write_out_table(self.b_lookup)
"""
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module handles events related to audiosplits and setting clip sync relationships.
"""
import pygtk
pygtk.require('2.0');
import gtk
import appconsts
import dialogutils
import edit
import editorstate
from editorstate import current_sequence
from editorstate import get_track
import gui
import movemodes
import tlinewidgets
import updater
import utils
# NOTE: THIS AND resync.py SHOULD PROBABLY BE THE SAME MODULE
parent_selection_data = None
# ----------------------------------- split audio
def split_audio_synched(popup_data):
"""
We do two separate edits to do this, so if user undoes this he'll need
to two undos, which may not be to user expectation as doing this is only one edit
"""
(parent_clip, child_clip, child_clip_track) = _do_split_audio_edit(popup_data)
# This is quarenteed because GUI option to do this is only available on this track
parent_track = current_sequence().tracks[current_sequence().first_video_index]
child_index = child_clip_track.clips.index(child_clip)
parent_clip_index = parent_track.clips.index(parent_clip)
data = {"child_index":child_index,
"child_track":child_clip_track,
"parent_index":parent_clip_index,
"parent_track":parent_track}
action = edit.set_sync_action(data)
action.do_edit()
def split_audio(popup_data):
_do_split_audio_edit(popup_data)
def _do_split_audio_edit(popup_data):
# NOTE: THIS HARD CODES ALL SPLITS TO HAPPEN ON TRACK A1, THIS MAY CHANGE
to_track = current_sequence().tracks[current_sequence().first_video_index - 1]
clip, track, item_id, x = popup_data
press_frame = tlinewidgets.get_frame(x)
index = current_sequence().get_clip_index(track, press_frame)
frame = track.clip_start(index)
audio_clip = current_sequence().create_file_producer_clip(clip.path)
audio_clip.media_type = appconsts.AUDIO
split_length = clip.clip_out - clip.clip_in + 1 # +1 out is inclusive and we're looking for length
data = { "parent_clip":clip,
"audio_clip":audio_clip,
"over_in":frame,
"over_out":frame + split_length,
"to_track":to_track}
action = edit.audio_splice_action(data)
action.do_edit()
return (clip, audio_clip, to_track)
# ---------------------------------------------- sync parent clips
def init_select_master_clip(popup_data):
clip, track, item_id, x = popup_data
frame = tlinewidgets.get_frame(x)
child_index = current_sequence().get_clip_index(track, frame)
if not (track.clips[child_index] == clip):
# This should never happen
print "big fu at _init_select_master_clip(...)"
return
gdk_window = gui.tline_display.get_parent_window();
gdk_window.set_cursor(gtk.gdk.Cursor(gtk.gdk.TCROSS))
editorstate.edit_mode = editorstate.SELECT_PARENT_CLIP
global parent_selection_data
parent_selection_data = (clip, child_index, track)
def select_sync_parent_mouse_pressed(event, frame):
_set_sync_parent_clip(event, frame)
gdk_window = gui.tline_display.get_parent_window();
gdk_window.set_cursor(gtk.gdk.Cursor(gtk.gdk.LEFT_PTR))
global parent_selection_data
parent_selection_data = None
# Edit consumes selection
movemodes.clear_selected_clips()
updater.repaint_tline()
def _set_sync_parent_clip(event, frame):
child_clip, child_index, child_clip_track = parent_selection_data
parent_track = tlinewidgets.get_track(event.y)
if parent_track != current_sequence().tracks[current_sequence().first_video_index]:
dialogutils.warning_message(_("Sync parent clips must be on track V1"),
_("Selected sync parent clip is on track ")+ utils.get_track_name(parent_track, current_sequence()) + _(".\nYou can only sync to clips that are on track V1."),
gui.editor_window.window,
True)
return
# this can't have parent clip already
if child_clip.sync_data != None:
return
if parent_track == None:
return
parent_clip_index = current_sequence().get_clip_index(parent_track, frame)
if parent_clip_index == -1:
return
# Parent and child can't be on the same track.
# Now that all parent clips must be on track V1 this is no longer shoild be possible.
if parent_track == child_clip_track:
print "parent_track == child_clip_track"
return
parent_clip = parent_track.clips[parent_clip_index]
# These cannot be chained.
# Now that all parent clips must be on track V1 this is no longer shoild be possible.
if parent_clip.sync_data != None:
print "parent_clip.sync_data != None"
return
data = {"child_index":child_index,
"child_track":child_clip_track,
"parent_index":parent_clip_index,
"parent_track":parent_track}
action = edit.set_sync_action(data)
action.do_edit()
def resync_clip(popup_data):
clip, track, item_id, x = popup_data
clip_list=[(clip, track)]
data = {"clips":clip_list}
action = edit.resync_some_clips_action(data)
action.do_edit()
updater.repaint_tline()
def resync_everything():
# Selection not valid after resync action
if movemodes.selected_track == -1:
movemodes.clear_selected_clips()
action = edit.resync_all_action({})
action.do_edit()
updater.repaint_tline()
def resync_selected():
if movemodes.selected_track == -1:
return
track = get_track(movemodes.selected_track)
clip_list = []
for index in range(movemodes.selected_range_in, movemodes.selected_range_out + 1):
clip_list.append((track.clips[index], track))
# Selection not valid after resync action
movemodes.clear_selected_clips()
# Chack if synced clips have same or consecutive parent clips
all_same_or_consecutive = True
master_id = -1
current_master_clip = -1
current_master_index = -1
master_track = current_sequence().first_video_track()
for t in clip_list:
clip, track = t
try:
if master_id == -1:
master_id = clip.sync_data.master_clip.id
current_master_clip = clip.sync_data.master_clip
current_master_index = master_track.clips.index(current_master_clip)
else:
if clip.sync_data.master_clip.id != master_id:
next_master_index = master_track.clips.index(clip.sync_data.master_clip)
if current_master_index + 1 == next_master_index:
# Masters are consecutive, save data to test next
master_id = clip.sync_data.master_clip.id
current_master_index = master_track.clips.index(current_master_clip)
else:
all_same_or_consecutive = False
except:
all_same_or_consecutive = False
# If clips are all for same or consecutive sync parent clips, sync them as a unit.
if len(clip_list) > 1 and all_same_or_consecutive == True:
data = {"clips":clip_list}
action = edit.resync_clips_sequence_action(data)
action.do_edit()
else: # Single or non-consecutive clips are synched separately
data = {"clips":clip_list}
action = edit.resync_some_clips_action(data)
action.do_edit()
updater.repaint_tline()
def clear_sync_relation(popup_data):
clip, track, item_id, x = popup_data
data = {"child_clip":clip,
"child_track":track}
action = edit.clear_sync_action(data)
action.do_edit()
# Edit consumes selection
movemodes.clear_selected_clips()
updater.repaint_tline()
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
This module handles functionality presented in Profiles Manager window.
"""
import pygtk
pygtk.require('2.0');
import gtk
import os
import dialogutils
import editorpersistance
import gui
import guicomponents
import guiutils
import mltprofiles
import render
import respaths
import utils
PROFILES_WIDTH = 480
PROFILES_HEIGHT = 690
PROFILE_MANAGER_LEFT = 265 # label column of profile manager panel
def profiles_manager_dialog():
dialog = gtk.Dialog(_("Profiles Manager"), None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(_("Close Manager").encode('utf-8'), gtk.RESPONSE_CLOSE))
panel2, user_profiles_view = _get_user_profiles_panel()
alignment2 = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment2.set_padding(12, 14, 12, 6)
alignment2.add(panel2)
panel1 = _get_factory_profiles_panel(user_profiles_view)
alignment1 = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment1.set_padding(12, 12, 12, 12)
alignment1.add(panel1)
pane = gtk.HBox(True, 2)
pane.pack_start(alignment1, True, True, 0)
pane.pack_start(alignment2, True, True, 0)
pane.set_size_request(PROFILES_WIDTH * 2, PROFILES_HEIGHT)
pane.show_all()
dialog.connect('response', dialogutils.dialog_destroy)
dialog.vbox.pack_start(pane, True, True, 0)
dialogutils.default_behaviour(dialog)
dialog.show_all()
return dialog
def _get_user_profiles_panel():
# User profiles view
user_profiles_list = guicomponents.ProfileListView()
user_profiles_list.fill_data_model(mltprofiles.get_user_profiles())
delete_selected_button = gtk.Button(_("Delete Selected"))
user_vbox = gtk.VBox(False, 2)
user_vbox.pack_start(user_profiles_list, True, True, 0)
user_vbox.pack_start(guiutils.get_right_justified_box([delete_selected_button]), False, False, 0)
# Create profile panel
default_profile_index = mltprofiles.get_default_profile_index()
default_profile = mltprofiles.get_default_profile()
load_profile_button = gtk.Button(_("Load Profile Values"))
load_profile_combo = gtk.combo_box_new_text()
profiles = mltprofiles.get_profiles()
for profile in profiles:
load_profile_combo.append_text(profile[0])
load_profile_combo.set_active(default_profile_index)
description = gtk.Entry()
description.set_text("User Created Profile")
f_rate_num = gtk.Entry()
f_rate_num.set_text(str(25))
f_rate_dem = gtk.Entry()
f_rate_dem.set_text(str(1))
width = gtk.Entry()
width.set_text(str(720))
height = gtk.Entry()
height.set_text(str(576))
s_rate_num = gtk.Entry()
s_rate_num.set_text(str(15))
s_rate_dem = gtk.Entry()
s_rate_dem.set_text(str(16))
d_rate_num = gtk.Entry()
d_rate_num.set_text(str(4))
d_rate_dem = gtk.Entry()
d_rate_dem.set_text(str(3))
progressive = gtk.CheckButton()
progressive.set_active(False)
save_button = gtk.Button(_("Save New Profile"))
widgets = (load_profile_combo, description, f_rate_num, f_rate_dem, width, height, s_rate_num,
s_rate_dem, d_rate_num, d_rate_dem, progressive)
_fill_new_profile_panel_widgets(default_profile, widgets)
# build panel
profile_row = gtk.HBox(False,0)
profile_row.pack_start(load_profile_combo, False, False, 0)
profile_row.pack_start(gtk.Label(), True, True, 0)
profile_row.pack_start(load_profile_button, False, False, 0)
row0 = guiutils.get_two_column_box(gtk.Label(_("Description.:")), description, PROFILE_MANAGER_LEFT)
row1 = guiutils.get_two_column_box(gtk.Label(_("Frame rate num.:")), f_rate_num, PROFILE_MANAGER_LEFT)
row2 = guiutils.get_two_column_box(gtk.Label(_("Frame rate den.:")), f_rate_dem, PROFILE_MANAGER_LEFT)
row3 = guiutils.get_two_column_box(gtk.Label(_("Width:")), width, PROFILE_MANAGER_LEFT)
row4 = guiutils.get_two_column_box(gtk.Label(_("Height:")), height, PROFILE_MANAGER_LEFT)
row5 = guiutils.get_two_column_box(gtk.Label(_("Sample aspect num.:")), s_rate_num, PROFILE_MANAGER_LEFT)
row6 = guiutils.get_two_column_box(gtk.Label(_("Sample aspect den.:")), s_rate_dem, PROFILE_MANAGER_LEFT)
row7 = guiutils.get_two_column_box(gtk.Label(_("Display aspect num.:")), d_rate_num, PROFILE_MANAGER_LEFT)
row8 = guiutils.get_two_column_box(gtk.Label(_("Display aspect den.:")), d_rate_dem, PROFILE_MANAGER_LEFT)
row9 = guiutils.get_two_column_box(gtk.Label(_("Progressive:")), progressive, PROFILE_MANAGER_LEFT)
save_row = gtk.HBox(False,0)
save_row.pack_start(gtk.Label(), True, True, 0)
save_row.pack_start(save_button, False, False, 0)
create_vbox = gtk.VBox(False, 2)
create_vbox.pack_start(profile_row, False, False, 0)
create_vbox.pack_start(guiutils.get_pad_label(10, 10), False, False, 0)
create_vbox.pack_start(row0, False, False, 0)
create_vbox.pack_start(row1, False, False, 0)
create_vbox.pack_start(row2, False, False, 0)
create_vbox.pack_start(row3, False, False, 0)
create_vbox.pack_start(row4, False, False, 0)
create_vbox.pack_start(row5, False, False, 0)
create_vbox.pack_start(row6, False, False, 0)
create_vbox.pack_start(row7, False, False, 0)
create_vbox.pack_start(row8, False, False, 0)
create_vbox.pack_start(row9, False, False, 0)
create_vbox.pack_start(guiutils.get_pad_label(10, 10), False, False, 0)
create_vbox.pack_start(save_row, False, False, 0)
# callbacks
load_profile_button.connect("clicked",lambda w,e: _load_values_clicked(widgets), None)
save_button.connect("clicked",lambda w,e: _save_profile_clicked(widgets, user_profiles_list), None)
delete_selected_button.connect("clicked",lambda w,e: _delete_user_profiles_clicked(user_profiles_list), None)
vbox = gtk.VBox(False, 2)
vbox.pack_start(guiutils.get_named_frame(_("Create User Profile"), create_vbox), False, False, 0)
vbox.pack_start(guiutils.get_named_frame(_("User Profiles"), user_vbox), True, True, 0)
return (vbox, user_profiles_list)
def _get_factory_profiles_panel(user_profiles_list):
# Factory
all_profiles_list = guicomponents.ProfileListView(_("Visible").encode('utf-8'))
all_profiles_list.fill_data_model(mltprofiles.get_factory_profiles())
hide_selected_button = gtk.Button(_("Hide Selected"))
hidden_profiles_list = guicomponents.ProfileListView(_("Hidden").encode('utf-8'))
hidden_profiles_list.fill_data_model(mltprofiles.get_hidden_profiles())
unhide_selected_button = gtk.Button(_("Unhide Selected"))
stop_icon = gtk.image_new_from_file(respaths.IMAGE_PATH + "bothways.png")
BUTTON_WIDTH = 120
BUTTON_HEIGHT = 28
hide_selected_button.set_size_request(BUTTON_WIDTH, BUTTON_HEIGHT)
unhide_selected_button.set_size_request(BUTTON_WIDTH, BUTTON_HEIGHT)
# callbacks
hide_selected_button.connect("clicked",lambda w,e: _hide_selected_clicked(all_profiles_list, hidden_profiles_list), None)
unhide_selected_button.connect("clicked",lambda w,e: _unhide_selected_clicked(all_profiles_list, hidden_profiles_list), None)
top_hbox = gtk.HBox(True, 2)
top_hbox.pack_start(all_profiles_list, True, True, 0)
top_hbox.pack_start(hidden_profiles_list, True, True, 0)
bottom_hbox = gtk.HBox(False, 2)
bottom_hbox.pack_start(hide_selected_button, False, False, 0)
bottom_hbox.pack_start(gtk.Label(), True, True, 0)
bottom_hbox.pack_start(stop_icon, False, False, 0)
bottom_hbox.pack_start(gtk.Label(), True, True, 0)
bottom_hbox.pack_start(unhide_selected_button, False, False, 0)
factory_vbox = gtk.VBox(False, 2)
factory_vbox.pack_start(top_hbox, True, True, 0)
factory_vbox.pack_start(bottom_hbox, False, False, 0)
vbox = gtk.VBox(True, 2)
vbox.pack_start(guiutils.get_named_frame(_("Factory Profiles"), factory_vbox), True, True, 0)
return vbox
def _fill_new_profile_panel_widgets(profile, widgets):
load_profile_combo, description, f_rate_num, f_rate_dem, width, height, s_rate_num, s_rate_dem, d_rate_num, d_rate_dem, progressive = widgets
description.set_text(_("User ") + profile.description())
f_rate_num.set_text(str(profile.frame_rate_num()))
f_rate_dem.set_text(str(profile.frame_rate_den()))
width.set_text(str(profile.width()))
height.set_text(str(profile.height()))
s_rate_num.set_text(str(profile.sample_aspect_num()))
s_rate_dem.set_text(str(profile.sample_aspect_den()))
d_rate_num.set_text(str(profile.display_aspect_num()))
d_rate_dem.set_text(str(profile.display_aspect_den()))
progressive.set_active(profile.progressive())
def _load_values_clicked(widgets):
load_profile_combo, description, f_rate_num, f_rate_dem, width, height, \
s_rate_num, s_rate_dem, d_rate_num, d_rate_dem, progressive = widgets
profile = mltprofiles.get_profile_for_index(load_profile_combo.get_active())
_fill_new_profile_panel_widgets(profile, widgets)
def _save_profile_clicked(widgets, user_profiles_view):
load_profile_combo, description, f_rate_num, f_rate_dem, width, height, \
s_rate_num, s_rate_dem, d_rate_num, d_rate_dem, progressive = widgets
profile_file_name = description.get_text().lower().replace(os.sep, "_").replace(" ","_")
file_contents = "description=" + description.get_text() + "\n"
file_contents += "frame_rate_num=" + f_rate_num.get_text() + "\n"
file_contents += "frame_rate_den=" + f_rate_dem.get_text() + "\n"
file_contents += "width=" + width.get_text() + "\n"
file_contents += "height=" + height.get_text() + "\n"
if progressive.get_active() == True:
prog_val = "1"
else:
prog_val = "0"
file_contents += "progressive=" + prog_val + "\n"
file_contents += "sample_aspect_num=" + s_rate_num.get_text() + "\n"
file_contents += "sample_aspect_den=" + s_rate_dem.get_text() + "\n"
file_contents += "display_aspect_num=" + d_rate_num.get_text() + "\n"
file_contents += "display_aspect_den=" + d_rate_dem.get_text() + "\n"
profile_path = utils.get_hidden_user_dir_path() + mltprofiles.USER_PROFILES_DIR + profile_file_name
if os.path.exists(profile_path):
dialogutils.warning_message(_("Profile '") + description.get_text() + _("' already exists!"), \
_("Delete profile and save again."), gui.editor_window.window)
return
profile_file = open(profile_path, "w")
profile_file.write(file_contents)
profile_file.close()
dialogutils.info_message(_("Profile '") + description.get_text() + _("' saved."), \
_("You can now create a new project using the new profile."), gui.editor_window.window)
mltprofiles.load_profile_list()
render.reload_profiles()
user_profiles_view.fill_data_model(mltprofiles.get_user_profiles())
def _delete_user_profiles_clicked(user_profiles_view):
delete_indexes = user_profiles_view.get_selected_indexes_list()
if len(delete_indexes) == 0:
return
primary_txt = _("Confirm user profile delete")
secondary_txt = _("This operation cannot be undone.")
dialogutils.warning_confirmation(_profiles_delete_confirm_callback, primary_txt, \
secondary_txt, gui.editor_window.window, \
(user_profiles_view, delete_indexes))
def _profiles_delete_confirm_callback(dialog, response_id, data):
if response_id != gtk.RESPONSE_ACCEPT:
dialog.destroy()
return
user_profiles_view, delete_indexes = data
for i in delete_indexes:
pname, profile = mltprofiles.get_user_profiles()[i]
profile_file_name = pname.lower().replace(os.sep, "_").replace(" ","_")
profile_path = utils.get_hidden_user_dir_path() + mltprofiles.USER_PROFILES_DIR + profile_file_name
print profile_path
try:
os.remove(profile_path)
except:
# This really should not happen
print "removed user profile already gone ???"
mltprofiles.load_profile_list()
user_profiles_view.fill_data_model(mltprofiles.get_user_profiles())
dialog.destroy()
def _hide_selected_clicked(visible_view, hidden_view):
visible_indexes = visible_view.get_selected_indexes_list()
prof_names = []
default_profile = mltprofiles.get_default_profile()
for i in visible_indexes:
pname, profile = mltprofiles.get_factory_profiles()[i]
if profile == default_profile:
dialogutils.warning_message("Can't hide default Profile",
"Profile '"+ profile.description() + "' is default profile and can't be hidden.",
None)
return
prof_names.append(pname)
editorpersistance.prefs.hidden_profile_names += prof_names
editorpersistance.save()
mltprofiles.load_profile_list()
visible_view.fill_data_model(mltprofiles.get_factory_profiles())
hidden_view.fill_data_model(mltprofiles.get_hidden_profiles())
def _unhide_selected_clicked(visible_view, hidden_view):
hidden_indexes = hidden_view.get_selected_indexes_list()
prof_names = []
for i in hidden_indexes:
pname, profile = mltprofiles.get_hidden_profiles()[i]
prof_names.append(pname)
editorpersistance.prefs.hidden_profile_names = list(set(editorpersistance.prefs.hidden_profile_names) - set(prof_names))
editorpersistance.save()
mltprofiles.load_profile_list()
visible_view.fill_data_model(mltprofiles.get_factory_profiles())
hidden_view.fill_data_model(mltprofiles.get_hidden_profiles())
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module creates GUI editors for editable mlt properties.
"""
import pygtk
pygtk.require('2.0');
import gtk
import appconsts
from editorstate import PROJECT
from editorstate import PLAYER
from editorstate import current_sequence
import extraeditors
import guiutils
import keyframeeditor
import mltfilters
import mlttransitions
import translations
import utils
EDITOR = "editor"
# editor types editor component
SLIDER = "slider" # gtk.HScale
BOOLEAN_CHECK_BOX = "booleancheckbox" # gtk.CheckButton
COMBO_BOX = "combobox" # gtk.Combobox
KEYFRAME_EDITOR = "keyframe_editor" # keyfremeeditor.KeyFrameEditor that has all the key frames relative to MEDIA start
KEYFRAME_EDITOR_CLIP = "keyframe_editor_clip" # keyfremeeditor.KeyFrameEditor that has all the key frames relative to CLIP start
KEYFRAME_EDITOR_RELEASE = "keyframe_editor_release" # HACK, HACK. used to prevent property update crashes in slider keyfremeeditor.KeyFrameEditor
COLOR_SELECT = "color_select" # gtk.ColorButton
GEOMETRY_EDITOR = "geometry_editor" # keyfremeeditor.GeometryEditor
WIPE_SELECT = "wipe_select" # gtk.Combobox with options from mlttransitions.wipe_lumas
COMBO_BOX_OPTIONS = "cbopts" # List of options for combo box editor displayed to user
LADSPA_SLIDER = "ladspa_slider" # gtk.HScale, does ladspa update for release changes(disconnect, reconnect)
CLIP_FRAME_SLIDER = "clip_frame_slider" # gtk.HScale, range 0 - clip length in frames
AFFINE_GEOM_4_SLIDER = "affine_filt_geom_slider" # 4 rows of gtk.HScales to set the position and size
COLOR_CORRECTOR = "color_corrector" # 3 band color corrector color circle and Lift Gain Gamma sliders
CR_CURVES = "crcurves" # Curves color editor with Catmull-Rom curve
COLOR_BOX = "colorbox" # One band color editor with color box interface
COLOR_LGG = "colorlgg" # Editor for ColorLGG filter
NO_EDITOR = "no_editor" # No editor displayed for property
COMPOSITE_EDITOR_BUILDER = "composite_properties" # Creates a single row editor for multiple properties of composite transition
REGION_EDITOR_BUILDER = "region_properties" # Creates a single row editor for multiple properties of region transition
ROTATION_GEOMETRY_EDITOR_BUILDER = "rotation_geometry_editor" # Creates a single editor for multiple geometry values
SCALE_DIGITS = "scale_digits" # Number of decimal digits displayed in a widget
def _p(name):
try:
return translations.param_names[name]
except KeyError:
return name
def get_editor_row(editable_property):
"""
Returns GUI component to edit provided editable property.
"""
try:
editor = editable_property.args[EDITOR]
except KeyError:
editor = SLIDER #default, if editor not specified
create_func = EDITOR_ROW_CREATORS[editor]
return create_func(editable_property)
def get_transition_extra_editor_rows(compositor, editable_properties):
"""
Returns list of extraeditors GUI components.
"""
extra_editors = compositor.transition.info.extra_editors
rows = []
for editor_name in extra_editors:
try:
create_func = EDITOR_ROW_CREATORS[editor_name]
editor_row = create_func(compositor, editable_properties)
rows.append(editor_row)
except KeyError:
print "get_transition_extra_editor_rows fail with:" + editor_name
return rows
def get_filter_extra_editor_rows(filt, editable_properties):
"""
Returns list of extraeditors GUI components.
"""
#print editable_properties
extra_editors = filt.info.extra_editors
rows = []
for editor_name in extra_editors:
try:
create_func = EDITOR_ROW_CREATORS[editor_name]
editor_row = create_func(filt, editable_properties)
rows.append(editor_row)
except KeyError:
print "get_filter_extra_editor_rows fail with:" + editor_name
return rows
# ------------------------------------------------- gui builders
def _get_two_column_editor_row(name, editor_widget):
name = _p(name)
label = gtk.Label(name + ":")
label_box = gtk.HBox()
label_box.pack_start(label, False, False, 0)
label_box.pack_start(gtk.Label(), True, True, 0)
label_box.set_size_request(appconsts.PROPERTY_NAME_WIDTH, appconsts.PROPERTY_ROW_HEIGHT)
hbox = gtk.HBox(False, 2)
hbox.pack_start(label_box, False, False, 4)
hbox.pack_start(editor_widget, True, True, 0)
return hbox
def _get_slider_row(editable_property, slider_name=None, compact=False):
adjustment = editable_property.get_input_range_adjustment()
adjustment.connect("value-changed", editable_property.adjustment_value_changed)
hslider = gtk.HScale()
hslider.set_adjustment(adjustment)
hslider.set_draw_value(False)
spin = gtk.SpinButton()
spin.set_numeric(True)
spin.set_adjustment(adjustment)
_set_digits(editable_property, hslider, spin)
if slider_name == None:
name = editable_property.get_display_name()
else:
name = slider_name
name = _p(name)
hbox = gtk.HBox(False, 4)
if compact:
name_label = gtk.Label(name + ":")
hbox.pack_start(name_label, False, False, 4)
hbox.pack_start(hslider, True, True, 0)
hbox.pack_start(spin, False, False, 4)
vbox = gtk.VBox(False)
if compact:
vbox.pack_start(hbox, False, False, 0)
else:
top_row = _get_two_column_editor_row(name, gtk.HBox())
vbox.pack_start(top_row, True, True, 0)
vbox.pack_start(hbox, False, False, 0)
return vbox
def _get_ladspa_slider_row(editable_property, slider_name=None):
adjustment = editable_property.get_input_range_adjustment()
hslider = gtk.HScale()
hslider.set_adjustment(adjustment)
hslider.set_draw_value(False)
hslider.connect("button-release-event", lambda w, e: _ladspa_slider_update(editable_property, adjustment))
spin = gtk.SpinButton()
spin.set_numeric(True)
spin.set_adjustment(adjustment)
spin.connect("button-release-event", lambda w, e: _ladspa_slider_update(editable_property, adjustment))
_set_digits(editable_property, hslider, spin)
hbox = gtk.HBox(False, 4)
hbox.pack_start(hslider, True, True, 0)
hbox.pack_start(spin, False, False, 4)
if slider_name == None:
name = editable_property.get_display_name()
else:
name = slider_name
top_row = _get_two_column_editor_row(name, gtk.HBox())
vbox = gtk.VBox(False)
vbox.pack_start(top_row, True, True, 0)
vbox.pack_start(hbox, False, False, 0)
return vbox
def _get_clip_frame_slider(editable_property):
# Exceptionally we set the edit range here,
# as the edit range is the clip length and
# is obivously not known at program start.
length = editable_property.get_clip_length() - 1
editable_property.input_range = (0, length)
editable_property.output_range = (0.0, length)
adjustment = editable_property.get_input_range_adjustment()
hslider = gtk.HScale()
hslider.set_adjustment(adjustment)
hslider.set_draw_value(False)
hslider.connect("button-release-event", lambda w, e: _clip_frame_slider_update(editable_property, adjustment))
spin = gtk.SpinButton()
spin.set_numeric(True)
spin.set_adjustment(adjustment)
spin.connect("button-release-event", lambda w, e: _clip_frame_slider_update(editable_property, adjustment))
hslider.set_digits(0)
spin.set_digits(0)
hbox = gtk.HBox(False, 4)
hbox.pack_start(hslider, True, True, 0)
hbox.pack_start(spin, False, False, 4)
name = editable_property.get_display_name()
return _get_two_column_editor_row(name, hbox)
def _get_affine_filt_geom_sliders(ep):
scr_width = PROJECT().profile.width()
scr_height = PROJECT().profile.width()
# "0=0,0:SCREENSIZE:100"
frame_value = ep.value.split("=")
tokens = frame_value[1].split(":")
pos_tokens = tokens[0].split("/")
size_tokens = tokens[1].split("x")
x_adj = gtk.Adjustment(float(pos_tokens[0]), float(-scr_width), float(scr_width), float(1))
y_adj = gtk.Adjustment(float(pos_tokens[1]), float(-scr_height), float(scr_height), float(1))
h_adj = gtk.Adjustment(float(size_tokens[1]), float(0), float(scr_height * 5), float(1))
x_slider, x_spin, x_row = _get_affine_slider("X", x_adj)
y_slider, y_spin, y_row = _get_affine_slider("Y", y_adj)
h_slider, h_spin, h_row = _get_affine_slider(_("Size/Height"), h_adj)
all_sliders = (x_slider, y_slider, h_slider)
x_slider.get_adjustment().connect("value-changed", lambda w: ep.slider_values_changed(all_sliders, scr_width))
x_spin.get_adjustment().connect("value-changed", lambda w: ep.slider_values_changed(all_sliders, scr_width))
y_slider.get_adjustment().connect("value-changed", lambda w: ep.slider_values_changed(all_sliders, scr_width))
y_spin.get_adjustment().connect("value-changed", lambda w: ep.slider_values_changed(all_sliders, scr_width))
h_slider.get_adjustment().connect("value-changed", lambda w: ep.slider_values_changed(all_sliders, scr_width))
h_spin.get_adjustment().connect("value-changed", lambda w: ep.slider_values_changed(all_sliders, scr_width))
vbox = gtk.VBox(False, 4)
vbox.pack_start(x_row, True, True, 0)
vbox.pack_start(y_row, True, True, 0)
vbox.pack_start(h_row, True, True, 0)
return vbox
def _get_affine_slider(name, adjustment):
hslider = gtk.HScale()
hslider.set_adjustment(adjustment)
hslider.set_draw_value(False)
spin = gtk.SpinButton()
spin.set_numeric(True)
spin.set_adjustment(adjustment)
hslider.set_digits(0)
spin.set_digits(0)
hbox = gtk.HBox(False, 4)
hbox.pack_start(hslider, True, True, 0)
hbox.pack_start(spin, False, False, 4)
return (hslider, spin, _get_two_column_editor_row(name, hbox))
def _get_boolean_check_box_row(editable_property):
check_button = gtk.CheckButton()
check_button.set_active(editable_property.value == "1")
check_button.connect("toggled", editable_property.boolean_button_toggled)
hbox = gtk.HBox(False, 4)
hbox.pack_start(check_button, False, False, 4)
hbox.pack_start(gtk.Label(), True, True, 0)
return _get_two_column_editor_row(editable_property.get_display_name(), hbox)
def _get_combo_box_row(editable_property):
combo_box = gtk.combo_box_new_text()
# Parse options and fill combo box
opts_str = editable_property.args[COMBO_BOX_OPTIONS]
values = []
opts = opts_str.split(",")
for option in opts:
sides = option.split(":")
values.append(sides[1])
opt = sides[0].replace("!"," ")# Spaces are separators in args
# and are replaced with "!" charactes for names
opt = translations.get_combo_option(opt)
combo_box.append_text(opt)
# Set initial value
selection = values.index(editable_property.value)
combo_box.set_active(selection)
combo_box.connect("changed", editable_property.combo_selection_changed, values)
return _get_two_column_editor_row(editable_property.get_display_name(), combo_box)
def _get_color_selector(editable_property):
gdk_color = editable_property.get_value_as_gdk_color()
color_button = gtk.ColorButton(gdk_color)
color_button.connect("color-set", editable_property.color_selected)
hbox = gtk.HBox(False, 4)
hbox.pack_start(color_button, False, False, 4)
hbox.pack_start(gtk.Label(), True, True, 0)
return _get_two_column_editor_row(editable_property.get_display_name(), hbox)
def _get_wipe_selector(editable_property):
"""
Returns GUI component for selecting wipe type.
"""
# Preset luma
combo_box = gtk.combo_box_new_text()
# Get options
keys = mlttransitions.wipe_lumas.keys()
# translate here
keys.sort()
for k in keys:
combo_box.append_text(k)
# Set initial value
k_index = -1
tokens = editable_property.value.split("/")
test_value = tokens[len(tokens) - 1]
for k,v in mlttransitions.wipe_lumas.iteritems():
if v == test_value:
k_index = keys.index(k)
combo_box.set_active(k_index)
preset_luma_row = _get_two_column_editor_row(editable_property.get_display_name(), combo_box)
# User luma
use_preset_luma_combo = gtk.combo_box_new_text()
use_preset_luma_combo.append_text(_("Preset Luma"))
use_preset_luma_combo.append_text(_("User Luma"))
dialog = gtk.FileChooserDialog(_("Select Luma File"), None,
gtk.FILE_CHOOSER_ACTION_OPEN,
(_("Cancel").encode('utf-8'), gtk.RESPONSE_REJECT,
_("OK").encode('utf-8'), gtk.RESPONSE_ACCEPT), None)
dialog.set_action(gtk.FILE_CHOOSER_ACTION_OPEN)
dialog.set_select_multiple(False)
file_filter = gtk.FileFilter()
file_filter.add_pattern("*.png")
file_filter.add_pattern("*.pgm")
file_filter.set_name(_("Wipe Luma files"))
dialog.add_filter(file_filter)
user_luma_select = gtk.FileChooserButton(dialog)
user_luma_select.set_size_request(210, 28)
user_luma_label = gtk.Label(_("Luma File:"))
if k_index == -1:
use_preset_luma_combo.set_active(1)
combo_box.set_sensitive(False)
combo_box.set_active(0)
user_luma_select.set_filename(editable_property.value)
else:
use_preset_luma_combo.set_active(0)
user_luma_select.set_sensitive(False)
user_luma_label.set_sensitive(False)
user_luma_row = gtk.HBox(False, 2)
user_luma_row.pack_start(use_preset_luma_combo, False, False, 0)
user_luma_row.pack_start(gtk.Label(), True, True, 0)
user_luma_row.pack_start(user_luma_label, False, False, 2)
user_luma_row.pack_start(user_luma_select, False, False, 0)
editor_pane = gtk.VBox(False)
editor_pane.pack_start(preset_luma_row, False, False, 4)
editor_pane.pack_start(user_luma_row, False, False, 4)
widgets = (combo_box, use_preset_luma_combo, user_luma_select, user_luma_label, keys)
combo_box.connect("changed", editable_property.combo_selection_changed, keys)
use_preset_luma_combo.connect("changed", _wipe_preset_combo_changed, editable_property, widgets)
dialog.connect('response', _wipe_lumafile_dialog_response, editable_property, widgets)
return editor_pane
def _wipe_preset_combo_changed(widget, ep, widgets):
combo_box, use_preset_luma_combo, user_luma_select, user_luma_label, keys = widgets
if widget.get_active() == 1:
combo_box.set_sensitive(False)
user_luma_select.set_sensitive(True)
user_luma_label.set_sensitive(True)
file_name = user_luma_select.get_filename()
if file_name != None:
ep.write_value(file_name)
else:
user_luma_select.set_sensitive(False)
user_luma_label.set_sensitive(False)
combo_box.set_sensitive(True)
ep.combo_selection_changed(combo_box, keys)
def _wipe_lumafile_dialog_response(dialog, response_id, ep, widgets):
combo_box, use_preset_luma_combo, user_luma_select, user_luma_label, keys = widgets
file_name = user_luma_select.get_filename()
if file_name != None:
ep.write_value(file_name)
def _create_composite_editor(clip, editable_properties):
aligned = filter(lambda ep: ep.name == "aligned", editable_properties)[0]
distort = filter(lambda ep: ep.name == "distort", editable_properties)[0]
operator = filter(lambda ep: ep.name == "operator", editable_properties)[0]
values = ["over","and","or","xor"]
deinterlace = filter(lambda ep: ep.name == "deinterlace", editable_properties)[0]
progressive = filter(lambda ep: ep.name == "progressive", editable_properties)[0]
force_values = [_("Nothing"),_("Progressive"),_("Deinterlace"),_("Both")]
combo_box = gtk.combo_box_new_text()
for val in force_values:
combo_box.append_text(val)
selection = _get_force_combo_index(deinterlace, progressive)
combo_box.set_active(selection)
combo_box.connect("changed", _compositor_editor_force_combo_box_callback, (deinterlace, progressive))
force_vbox = gtk.VBox(False, 4)
force_vbox.pack_start(gtk.Label(_("Force")), True, True, 0)
force_vbox.pack_start(combo_box, True, True, 0)
hbox = gtk.HBox(False, 4)
hbox.pack_start(guiutils.get_pad_label(3, 5), False, False, 0)
hbox.pack_start(_get_boolean_check_box_button_column(_("Align"), aligned), False, False, 0)
hbox.pack_start(_get_boolean_check_box_button_column(_("Distort"), distort), False, False, 0)
hbox.pack_start(gtk.Label(), True, True, 0)
hbox.pack_start(_get_combo_box_column(_("Alpha"), values, operator), False, False, 0)
hbox.pack_start(gtk.Label(), True, True, 0)
hbox.pack_start(force_vbox, False, False, 0)
hbox.pack_start(guiutils.get_pad_label(3, 5), False, False, 0)
return hbox
def _compositor_editor_force_combo_box_callback(combo_box, data):
value = combo_box.get_active()
deinterlace, progressive = data
# these must correspond to hardcoded values ["Nothing","Progressive","Deinterlace","Both"] above
if value == 0:
deinterlace.write_value("0")
progressive.write_value("0")
elif value == 1:
deinterlace.write_value("0")
progressive.write_value("1")
elif value == 2:
deinterlace.write_value("1")
progressive.write_value("0")
else:
deinterlace.write_value("1")
progressive.write_value("1")
def _create_rotion_geometry_editor(clip, editable_properties):
# Build a custom object that duck types for TransitionEditableProperty to use in editor
ep = utils.EmptyClass()
# pack real properties to go
ep.x = filter(lambda ep: ep.name == "x", editable_properties)[0]
ep.y = filter(lambda ep: ep.name == "y", editable_properties)[0]
ep.x_scale = filter(lambda ep: ep.name == "x scale", editable_properties)[0]
ep.y_scale = filter(lambda ep: ep.name == "y scale", editable_properties)[0]
ep.rotation = filter(lambda ep: ep.name == "rotation", editable_properties)[0]
ep.opacity = filter(lambda ep: ep.name == "opacity", editable_properties)[0]
# Screen width and height are needeed for frei0r conversions
ep.profile_width = current_sequence().profile.width()
ep.profile_height = current_sequence().profile.height()
# duck type methods, using opacity is not meaningful, any property with clip member could do
ep.get_clip_tline_pos = lambda : ep.opacity.clip.clip_in # clip is compositor, compositor in and out points staright in timeline frames
ep.get_clip_length = lambda : ep.opacity.clip.clip_out - ep.opacity.clip.clip_in + 1
ep.get_input_range_adjustment = lambda : gtk.Adjustment(float(100), float(0), float(100), float(1))
ep.get_display_name = lambda : "Opacity"
ep.get_pixel_aspect_ratio = lambda : (float(current_sequence().profile.sample_aspect_num()) / current_sequence().profile.sample_aspect_den())
ep.get_in_value = lambda out_value : out_value # hard coded for opacity 100 -> 100 range
ep.write_out_keyframes = lambda w_kf : keyframeeditor.rotating_ge_write_out_keyframes(ep, w_kf)
# duck type members
x_tokens = ep.x.value.split(";")
y_tokens = ep.y.value.split(";")
x_scale_tokens = ep.x_scale.value.split(";")
y_scale_tokens = ep.y_scale.value.split(";")
rotation_tokens = ep.rotation.value.split(";")
opacity_tokens = ep.opacity.value.split(";")
value = ""
for i in range(0, len(x_tokens)): # these better match, same number of keyframes for all values, or this will not work
frame, x = x_tokens[i].split("=")
frame, y = y_tokens[i].split("=")
frame, x_scale = x_scale_tokens[i].split("=")
frame, y_scale = y_scale_tokens[i].split("=")
frame, rotation = rotation_tokens[i].split("=")
frame, opacity = opacity_tokens[i].split("=")
frame_str = str(frame) + "=" + str(x) + ":" + str(y) + ":" + str(x_scale) + ":" + str(y_scale) + ":" + str(rotation) + ":" + str(opacity)
value += frame_str + ";"
ep.value = value.strip(";")
kf_edit = keyframeeditor.RotatingGeometryEditor(ep, False)
return kf_edit
def _create_region_editor(clip, editable_properties):
aligned = filter(lambda ep: ep.name == "composite.aligned", editable_properties)[0]
distort = filter(lambda ep: ep.name == "composite.distort", editable_properties)[0]
operator = filter(lambda ep: ep.name == "composite.operator", editable_properties)[0]
values = ["over","and","or","xor"]
deinterlace = filter(lambda ep: ep.name == "composite.deinterlace", editable_properties)[0]
progressive = filter(lambda ep: ep.name == "composite.progressive", editable_properties)[0]
force_values = [_("Nothing"),_("Progressive"),_("Deinterlace"),_("Both")]
combo_box = gtk.combo_box_new_text()
for val in force_values:
combo_box.append_text(val)
selection = _get_force_combo_index(deinterlace, progressive)
combo_box.set_active(selection)
combo_box.connect("changed", _compositor_editor_force_combo_box_callback, (deinterlace, progressive))
force_vbox = gtk.VBox(False, 4)
force_vbox.pack_start(gtk.Label(_("Force")), True, True, 0)
force_vbox.pack_start(combo_box, True, True, 0)
hbox = gtk.HBox(False, 4)
hbox.pack_start(guiutils.get_pad_label(3, 5), False, False, 0)
hbox.pack_start(_get_boolean_check_box_button_column(_("Align"), aligned), False, False, 0)
hbox.pack_start(_get_boolean_check_box_button_column(_("Distort"), distort), False, False, 0)
hbox.pack_start(gtk.Label(), True, True, 0)
hbox.pack_start(_get_combo_box_column(_("Alpha"), values, operator), False, False, 0)
hbox.pack_start(gtk.Label(), True, True, 0)
hbox.pack_start(force_vbox, False, False, 0)
hbox.pack_start(guiutils.get_pad_label(3, 5), False, False, 0)
return hbox
def _create_color_grader(filt, editable_properties):
color_grader = extraeditors.ColorGrader(editable_properties)
vbox = gtk.VBox(False, 4)
vbox.pack_start(gtk.Label(), True, True, 0)
vbox.pack_start(color_grader.widget, False, False, 0)
vbox.pack_start(gtk.Label(), True, True, 0)
vbox.no_separator = True
return vbox
def _create_crcurves_editor(filt, editable_properties):
curves_editor = extraeditors.CatmullRomFilterEditor(editable_properties)
vbox = gtk.VBox(False, 4)
vbox.pack_start(curves_editor.widget, False, False, 0)
vbox.pack_start(gtk.Label(), True, True, 0)
vbox.no_separator = True
return vbox
def _create_colorbox_editor(filt, editable_properties):
colorbox_editor = extraeditors.ColorBoxFilterEditor(editable_properties)
vbox = gtk.VBox(False, 4)
vbox.pack_start(colorbox_editor.widget, False, False, 0)
vbox.pack_start(gtk.Label(), True, True, 0)
vbox.no_separator = True
return vbox
def _create_color_lgg_editor(filt, editable_properties):
color_lgg_editor = extraeditors.ColorLGGFilterEditor(editable_properties)
vbox = gtk.VBox(False, 4)
vbox.pack_start(color_lgg_editor.widget, False, False, 0)
vbox.pack_start(gtk.Label(), True, True, 0)
vbox.no_separator = True
return vbox
def _get_force_combo_index(deinterlace, progressive):
# These correspond to hardcoded values ["Nothing","Progressive","Deinterlace","Both"] above
if int(deinterlace.value) == 0:
if int(progressive.value) == 0:
return 0
else:
return 1
else:
if int(progressive.value) == 0:
return 2
else:
return 3
def _get_keyframe_editor(editable_property):
return keyframeeditor.KeyFrameEditor(editable_property)
def _get_keyframe_editor_clip(editable_property):
return keyframeeditor.KeyFrameEditor(editable_property, False)
def _get_keyframe_editor_release(editable_property):
editor = keyframeeditor.KeyFrameEditor(editable_property)
editor.connect_to_update_on_release()
return editor
def _get_geometry_editor(editable_property):
return keyframeeditor.GeometryEditor(editable_property, False)
def _get_no_editor():
return None
def _set_digits(editable_property, scale, spin):
try:
digits_str = editable_property.args[SCALE_DIGITS]
digits = int(digits_str)
except:
return
scale.set_digits(digits)
spin.set_digits(digits)
# -------------------------------------------------------- gui utils funcs
def _get_boolean_check_box_button_column(name, editable_property):
check_button = gtk.CheckButton()
check_button.set_active(editable_property.value == "1")
check_button.connect("toggled", editable_property.boolean_button_toggled)
check_align = gtk.Alignment(0.5, 0.0)
check_align.add(check_button)
vbox = gtk.VBox(False, 0)
vbox.pack_start(gtk.Label(name), True, True, 0)
vbox.pack_start(check_align, True, True, 0)
return vbox
def _get_combo_box_column(name, values, editable_property):
combo_box = gtk.combo_box_new_text()
for val in values:
val = translations.get_combo_option(val)
combo_box.append_text(val)
# Set initial value
selection = values.index(editable_property.value)
combo_box.set_active(selection)
combo_box.connect("changed", editable_property.combo_selection_changed, values)
vbox = gtk.VBox(False, 4)
vbox.pack_start(gtk.Label(name), True, True, 0)
vbox.pack_start(combo_box, True, True, 0)
return vbox
# ------------------------------------ SPECIAL VALUE UPDATE METHODS
# LADSPA filters do not respond to MLT property updates and
# need to be recreated to update output
def _ladspa_slider_update(editable_property, adjustment):
# ...or segphault
PLAYER().stop_playback()
# Change property value
editable_property.adjustment_value_changed(adjustment)
# Update output by cloning and replacing filter
ladspa_filter = editable_property._get_filter_object()
filter_clone = mltfilters.clone_filter_object(ladspa_filter, PROJECT().profile)
clip = editable_property.track.clips[editable_property.clip_index]
mltfilters.detach_all_filters(clip)
clip.filters.pop(editable_property.filter_index)
clip.filters.insert(editable_property.filter_index, filter_clone)
mltfilters.attach_all_filters(clip)
def _clip_frame_slider_update(editable_property, adjustment):
PLAYER().stop_playback()
editable_property.adjustment_value_changed(adjustment)
# editor types -> creator functions
EDITOR_ROW_CREATORS = { \
SLIDER:lambda ep :_get_slider_row(ep),
BOOLEAN_CHECK_BOX:lambda ep :_get_boolean_check_box_row(ep),
COMBO_BOX:lambda ep :_get_combo_box_row(ep),
KEYFRAME_EDITOR: lambda ep : _get_keyframe_editor(ep),
KEYFRAME_EDITOR_CLIP: lambda ep : _get_keyframe_editor_clip(ep),
KEYFRAME_EDITOR_RELEASE: lambda ep : _get_keyframe_editor_release(ep),
GEOMETRY_EDITOR: lambda ep : _get_geometry_editor(ep),
AFFINE_GEOM_4_SLIDER: lambda ep : _get_affine_filt_geom_sliders(ep),
COLOR_SELECT: lambda ep: _get_color_selector(ep),
WIPE_SELECT: lambda ep: _get_wipe_selector(ep),
LADSPA_SLIDER: lambda ep: _get_ladspa_slider_row(ep),
CLIP_FRAME_SLIDER: lambda ep: _get_clip_frame_slider(ep),
NO_EDITOR: lambda ep: _get_no_editor(),
COMPOSITE_EDITOR_BUILDER: lambda comp, editable_properties: _create_composite_editor(comp, editable_properties),
REGION_EDITOR_BUILDER: lambda comp, editable_properties: _create_region_editor(comp, editable_properties),
ROTATION_GEOMETRY_EDITOR_BUILDER: lambda comp, editable_properties: _create_rotion_geometry_editor(comp, editable_properties),
COLOR_CORRECTOR: lambda filt, editable_properties: _create_color_grader(filt, editable_properties),
CR_CURVES: lambda filt, editable_properties:_create_crcurves_editor(filt, editable_properties),
COLOR_BOX: lambda filt, editable_properties:_create_colorbox_editor(filt, editable_properties),
COLOR_LGG: lambda filt, editable_properties:_create_color_lgg_editor(filt, editable_properties)
}
"""
# example code for using slider editor with NON-MLT property
#hue = filter(lambda ep: ep.name == "hue", editable_properties)[0]
#hue_row = _get_slider_row(hue, None, True)
#saturation = filter(lambda ep: ep.name == "saturation", editable_properties)[0]
#saturation_row = _get_slider_row(saturation, None, True)
#value = filter(lambda ep: ep.name == "value", editable_properties)[0]
#value_row = _get_slider_row(value, None, True)
#colorbox_editor = extraeditors.ColorBoxFilterEditor(editable_properties, [hue_row, saturation_row, value_row])
#hue.adjustment_listener = colorbox_editor.hue_changed
#saturation.adjustment_listener = colorbox_editor.saturation_changed
#value.adjustment_listener = colorbox_editor.value_changed
"""
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module contains utility methods for creating GUI objects.
"""
import pygtk
pygtk.require('2.0');
import gtk
import time
import threading
import appconsts
import respaths
import translations
TWO_COLUMN_BOX_HEIGHT = 20
def bold_label(str):
label = gtk.Label(bold_text(str))
label.set_use_markup(True)
return label
def bold_text(str):
return "<b>" + str + "</b>"
def get_left_justified_box(widgets):
hbox = gtk.HBox()
for widget in widgets:
hbox.pack_start(widget, False, False, 0)
hbox.pack_start(gtk.Label(), True, True, 0)
return hbox
def get_right_justified_box(widgets):
hbox = gtk.HBox()
hbox.pack_start(gtk.Label(), True, True, 0)
for widget in widgets:
hbox.pack_start(widget, False, False, 0)
return hbox
def get_sides_justified_box(widgets, count_of_widgets_on_the_left=1):
hbox = gtk.HBox()
wgets_added = 0
for widget in widgets:
hbox.pack_start(widget, False, False, 0)
wgets_added +=1
if wgets_added == count_of_widgets_on_the_left:
hbox.pack_start(gtk.Label(), True, True, 0)
return hbox
def get_centered_box(widgets):
hbox = gtk.HBox()
hbox.pack_start(gtk.Label(), True, True, 0)
for widget in widgets:
hbox.pack_start(widget, False, False, 0)
hbox.pack_start(gtk.Label(), True, True, 0)
return hbox
def get_vbox(widgets, add_pad_label=True, padding=2):
vbox = gtk.VBox(False, padding)
for widget in widgets:
vbox.pack_start(widget, False, False, 0)
if add_pad_label:
vbox.pack_start(gtk.Label(), True, True, 0)
return vbox
def get_single_column_box(widgets):
vbox = gtk.VBox()
for widget in widgets:
vbox.pack_start(get_left_justified_box([widget]), False, False, 0)
vbox.pack_start(gtk.Label(), True, True, 0)
return vbox
def get_two_column_box(widget1, widget2, left_width):
hbox = gtk.HBox()
left_box = get_left_justified_box([widget1])
left_box.set_size_request(left_width, TWO_COLUMN_BOX_HEIGHT)
hbox.pack_start(left_box, False, True, 0)
hbox.pack_start(widget2, True, True, 0)
return hbox
def get_two_column_box_right_pad(widget1, widget2, left_width, right_pad):
left_box = get_left_justified_box([widget1])
left_box.set_size_request(left_width, TWO_COLUMN_BOX_HEIGHT)
right_widget_box = get_left_justified_box([widget2])
pad_label = get_pad_label(right_pad, 5)
right_box = gtk.HBox()
right_box.pack_start(right_widget_box, True, True, 0)
right_box.pack_start(pad_label, False, False, 0)
hbox = gtk.HBox()
hbox.pack_start(left_box, False, True, 0)
hbox.pack_start(right_box, True, True, 0)
return hbox
def get_checkbox_row_box(checkbox, widget2):
hbox = gtk.HBox()
hbox.pack_start(checkbox, False, False, 0)
hbox.pack_start(widget2, False, False, 0)
hbox.pack_start(gtk.Label(), True, True, 0)
return hbox
def get_two_row_box(widget1, widget2):
# widget 1 is left justified
top = get_left_justified_box([widget1])
box = gtk.VBox(False, 2)
box.pack_start(top, False, False, 4)
box.pack_start(widget2, False, False, 0)
return box
def get_image_button(img_file_name, width, height):
button = gtk.Button()
icon = gtk.image_new_from_file(respaths.IMAGE_PATH + img_file_name)
button_box = gtk.HBox()
button_box.pack_start(icon, False, False, 0)
button.add(button_box)
button.set_size_request(width, height)
return button
def get_pad_label(w, h):
label = gtk.Label()
label.set_size_request(w, h)
return label
def get_multiplied_color(color, m):
"""
Used to create lighter and darker hues of colors.
"""
return (color[0] * m, color[1] * m, color[2] * m)
def get_slider_row(editable_property, listener, slider_name=None):
adjustment = editable_property.get_input_range_adjustment()
editable_property.value_changed_ID = adjustment.connect("value-changed", listener) # patching in to make available for disconnect
editable_property.adjustment = adjustment # patching in to make available for disconnect
hslider = gtk.HScale()
hslider.set_adjustment(adjustment)
hslider.set_draw_value(False)
spin = gtk.SpinButton()
spin.set_numeric(True)
spin.set_adjustment(adjustment)
hbox = gtk.HBox(False, 4)
hbox.pack_start(hslider, True, True, 0)
hbox.pack_start(spin, False, False, 4)
if slider_name == None:
name = editable_property.get_display_name()
else:
name = slider_name
name = translations.get_param_name(name)
return (get_two_column_editor_row(name, hbox), hslider)
def get_non_property_slider_row(lower, upper, step, value=0, listener=None):
hslider = gtk.HScale()
hslider.set_draw_value(False)
adjustment = hslider.get_adjustment()
adjustment.set_lower(lower)
adjustment.set_upper(upper)
adjustment.set_step_increment(step)
adjustment.set_value(value)
if listener != None:
adjustment.connect("value-changed", listener) # patching in to make available for disconnect
spin = gtk.SpinButton()
spin.set_numeric(True)
spin.set_adjustment(adjustment)
hbox = gtk.HBox(False, 4)
hbox.pack_start(hslider, True, True, 0)
hbox.pack_start(spin, False, False, 4)
return (hbox, hslider)
def get_two_column_editor_row(name, editor_widget):
label = gtk.Label(name + ":")
label_box = gtk.HBox()
label_box.pack_start(label, False, False, 0)
label_box.pack_start(gtk.Label(), True, True, 0)
label_box.set_size_request(appconsts.PROPERTY_NAME_WIDTH, appconsts.PROPERTY_ROW_HEIGHT)
hbox = gtk.HBox(False, 2)
hbox.pack_start(label_box, False, False, 4)
hbox.pack_start(editor_widget, True, True, 0)
return hbox
def get_no_pad_named_frame(name, panel):
return get_named_frame(name, panel, 0, 0, 0)
def get_named_frame_with_vbox(name, widgets, left_padding=12, right_padding=6, right_out_padding=4):
vbox = gtk.VBox()
for widget in widgets:
vbox.pack_start(widget, False, False, 0)
return get_named_frame(name, vbox, left_padding, right_padding, right_out_padding)
def get_named_frame(name, widget, left_padding=12, right_padding=6, right_out_padding=4):
"""
Gnome style named panel
"""
if name != None:
label = bold_label(name)
label.set_justify(gtk.JUSTIFY_LEFT)
label_box = gtk.HBox()
label_box.pack_start(label, False, False, 0)
label_box.pack_start(gtk.Label(), True, True, 0)
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(right_padding, 0, left_padding, 0)
alignment.add(widget)
frame = gtk.VBox()
if name != None:
frame.pack_start(label_box, False, False, 0)
frame.pack_start(alignment, True, True, 0)
out_align = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
out_align.set_padding(4, 4, 0, right_out_padding)
out_align.add(frame)
return out_align
def get_in_centering_alignment(widget, xsc=0.0, ysc=0.0):
align = gtk.Alignment(xalign=0.5, yalign=0.5, xscale=xsc, yscale=ysc)
align.add(widget)
return align
def pad_label(w, h):
pad_label = gtk.Label()
pad_label.set_size_request(w, h)
return pad_label
def get_sized_button(lable, w, h, clicked_listener=None):
b = gtk.Button(lable)
if clicked_listener != None:
b.connect("clicked", lambda w,e: clicked_listener())
b.set_size_request(w, h)
return b
def get_render_button():
render_button = gtk.Button()
render_icon = gtk.image_new_from_stock(gtk.STOCK_MEDIA_RECORD,
gtk.ICON_SIZE_BUTTON)
render_button_box = gtk.HBox()
render_button_box.pack_start(get_pad_label(10, 10), False, False, 0)
render_button_box.pack_start(render_icon, False, False, 0)
render_button_box.pack_start(get_pad_label(5, 10), False, False, 0)
render_button_box.pack_start(gtk.Label(_("Render")), False, False, 0)
render_button_box.pack_start(get_pad_label(10, 10), False, False, 0)
render_button.add(render_button_box)
return render_button
def get_menu_item(text, callback, data, sensitive=True):
item = gtk.MenuItem(text)
item.connect("activate", callback, data)
item.show()
item.set_sensitive(sensitive)
return item
def add_separetor(menu):
sep = gtk.SeparatorMenuItem()
sep.show()
menu.add(sep)
def get_gtk_image_from_file(source_path, image_height):
img = gtk.Image()
p_map = get_pixmap_from_file(source_path, image_height)
img.set_from_pixmap(p_map, None)
return img
def get_pixmap_from_file(source_path, image_height):
pixbuf = gtk.gdk.pixbuf_new_from_file(source_path)
icon_width = int((float(pixbuf.get_width()) / float(pixbuf.get_height())) * image_height)
s_pbuf = pixbuf.scale_simple(icon_width, image_height, gtk.gdk.INTERP_BILINEAR)
p_map, mask = s_pbuf.render_pixmap_and_mask()
return p_map
class PulseThread(threading.Thread):
def __init__(self, proress_bar):
threading.Thread.__init__(self)
self.proress_bar = proress_bar
def run(self):
self.exited = False
self.running = True
while self.running:
gtk.gdk.threads_enter()
self.proress_bar.pulse()
gtk.gdk.threads_leave()
time.sleep(0.1)
self.exited = True
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module loads render options, provides them in displayable form
and builds a mlt.Consumer for rendering on request.
Rendering is done in app.player object of class mltplayer.Player
"""
import pygtk
pygtk.require('2.0');
import gtk
import mlt
import md5
import os
import time
import threading
import dialogutils
from editorstate import current_sequence
from editorstate import PROJECT
from editorstate import PLAYER
import editorpersistance
import gui
import guicomponents
import guiutils
import mltprofiles
import mltrefhold
import projectdata
import projectinfogui
import renderconsumer
import rendergui
import sequence
import utils
# User defined render agrs file extension
FFMPEG_OPTS_SAVE_FILE_EXTENSION = ".rargs"
open_media_file_callback = None # monkeypatched in by app.py to avoid circular imports
render_start_time = 0
widgets = utils.EmptyClass()
progress_window = None
aborted = False
# Motion clip rendering
motion_renderer = None
motion_progress_update = None
# Transition clip rendering
transition_render_done_callback = None
# ---------------------------------- rendering action and dialogs
class RenderLauncher(threading.Thread):
def __init__(self, render_consumer, start_frame, end_frame):
threading.Thread.__init__(self)
self.render_consumer = render_consumer
# Hack. We seem to be getting range rendering starting 1-2 frame too late.
# Changing in out frame logic in monitor is not a good idea,
# especially as this may be mlt issue, so we just try this.
start_frame += -1
if start_frame < 0:
start_frame = 0
self.start_frame = start_frame
self.end_frame = end_frame
def run(self):
callbacks = utils.EmptyClass()
callbacks.set_render_progress_gui = set_render_progress_gui
callbacks.save_render_start_time = save_render_start_time
callbacks.exit_render_gui = exit_render_gui
callbacks.maybe_open_rendered_file_in_bin = maybe_open_rendered_file_in_bin
PLAYER().set_render_callbacks(callbacks)
PLAYER().start_rendering(self.render_consumer, self.start_frame, self.end_frame)
def render_timeline():
if len(widgets.file_panel.movie_name.get_text()) == 0:
primary_txt = _("Render file name entry is empty")
secondary_txt = _("You have to provide a name for the file to be rendered.")
dialogutils.warning_message(primary_txt, secondary_txt, gui.editor_window.window)
return
if os.path.exists(get_file_path()):
primary_txt = _("File: ") + get_file_path() + _(" already exists!")
secondary_txt = _("Do you want to overwrite existing file?")
dialogutils.warning_confirmation(_render_overwrite_confirm_callback, primary_txt, secondary_txt, gui.editor_window.window)
else:
_do_rendering()
def _render_overwrite_confirm_callback(dialog, response_id):
dialog.destroy()
if response_id == gtk.RESPONSE_ACCEPT:
_do_rendering()
def _do_rendering():
print "timeline render..."
global aborted
aborted = False
render_consumer = get_render_consumer()
if render_consumer == None:
return
# Set render start and end points
if widgets.range_cb.get_active() == 0:
start_frame = 0
end_frame = -1 # renders till finish
else:
start_frame = current_sequence().tractor.mark_in
end_frame = current_sequence().tractor.mark_out
# Only render a range if it is defined.
if start_frame == -1 or end_frame == -1:
if widgets.range_cb.get_active() == 1:
rendergui.no_good_rander_range_info()
return
file_path = get_file_path()
project_event = projectdata.ProjectEvent(projectdata.EVENT_RENDERED, file_path)
PROJECT().events.append(project_event)
projectinfogui.update_project_info()
# See if project and render fps match
cnum = render_consumer.profile().frame_rate_num()
cden = render_consumer.profile().frame_rate_den()
pnum = PROJECT().profile.frame_rate_num()
pden = PROJECT().profile.frame_rate_den()
if (cnum == pnum) and (cden == pden):
frames_rates_match = True
else:
frames_rates_match = False
global progress_window
progress_window = rendergui.render_progress_dialog(_render_cancel_callback,
gui.editor_window.window,
frames_rates_match)
set_render_gui()
render_launch = RenderLauncher(render_consumer, start_frame, end_frame)
render_launch.start()
def _render_cancel_callback(dialog, response_id):
global aborted
aborted = True
dialog.destroy()
PLAYER().consumer.stop()
PLAYER().producer.set_speed(0)
# -------------------------------------------------- render consumer
def get_render_consumer():
file_path = get_file_path()
if file_path == None:
return None
profile = get_current_profile()
if widgets.render_type_panel.type_combo.get_active() == 1: # Preset encodings
encoding_option = renderconsumer.non_user_encodings[widgets.render_type_panel.presets_selector.widget.get_active()]
if encoding_option.type != "img_seq":
consumer = renderconsumer.get_render_consumer_for_encoding(file_path,
profile,
encoding_option)
else: # Image Sequence rendering consumers need to be created a bit differently
consumer = renderconsumer.get_img_seq_render_consumer(file_path,
profile,
encoding_option)
return consumer
if widgets.args_panel.use_args_check.get_active() == False:
# Using options comboboxes
encoding_option_index = widgets.encoding_panel.encoding_selector.widget.get_active()
quality_option_index = widgets.encoding_panel.quality_selector.widget.get_active()
consumer = renderconsumer.get_render_consumer_for_encoding_and_quality( file_path,
profile,
encoding_option_index,
quality_option_index)
else:
buf = widgets.args_panel.opts_view.get_buffer()
consumer, error = renderconsumer.get_render_consumer_for_text_buffer(file_path,
profile,
buf)
if error != None:
dialogutils.warning_message("FFMPeg Args Error", error, gui.editor_window.window)
return None
return consumer
def get_args_vals_list_for_current_selections():
profile = get_current_profile()
encoding_option_index = widgets.encoding_panel.encoding_selector.widget.get_active()
quality_option_index = widgets.encoding_panel.quality_selector.widget.get_active()
if widgets.render_type_panel.type_combo.get_active() == 1: # Preset encodings
args_vals_list = renderconsumer.get_args_vals_tuples_list_for_encoding_and_quality( profile,
encoding_option_index,
-1)
elif widgets.args_panel.use_args_check.get_active() == False: # User encodings
args_vals_list = renderconsumer.get_args_vals_tuples_list_for_encoding_and_quality( profile,
encoding_option_index,
quality_option_index)
else: # Manual args encodings
buf = widgets.args_panel.opts_view.get_buffer()
args_vals_list, error = renderconsumer.get_ffmpeg_opts_args_vals_tuples_list(buf)
if error != None:
dialogutils.warning_message("FFMPeg Args Error", error, gui.editor_window.window)
return None
return args_vals_list
def get_file_path():
folder = widgets.file_panel.out_folder.get_filenames()[0]
filename = widgets.file_panel.movie_name.get_text()
if widgets.args_panel.use_args_check.get_active() == False:
extension = widgets.file_panel.extension_label.get_text()
else:
extension = "." + widgets.args_panel.ext_entry.get_text()
return folder + "/" + filename + extension
# --------------------------------------------------- gui
def create_widgets(normal_height):
"""
Widgets for editing render properties and viewing render progress.
"""
widgets.file_panel = rendergui.RenderFilePanel()
widgets.render_type_panel = rendergui.RenderTypePanel(_render_type_changed, _preset_selection_changed)
widgets.profile_panel = rendergui.RenderProfilePanel(_out_profile_changed)
widgets.encoding_panel = rendergui.RenderEncodingPanel(widgets.file_panel.extension_label)
widgets.args_panel = rendergui.RenderArgsPanel(normal_height,
_save_opts_pressed, _load_opts_pressed,
_display_selection_in_opts_view)
# Range, Render, Reset, Render Queue
widgets.render_button = guiutils.get_render_button()
widgets.range_cb = rendergui.get_range_selection_combo()
widgets.reset_button = gtk.Button(_("Reset"))
widgets.reset_button.connect("clicked", lambda w: set_default_values_for_widgets())
widgets.queue_button = gtk.Button(_("To Queue"))
widgets.queue_button.set_tooltip_text(_("Save Project in Render Queue"))
# Tooltips
widgets.range_cb.set_tooltip_text(_("Select render range"))
widgets.reset_button.set_tooltip_text(_("Reset all render options to defaults"))
widgets.render_button.set_tooltip_text(_("Begin Rendering"))
def set_default_values_for_widgets(movie_name_too=False):
if len(renderconsumer.encoding_options) == 0:# this won't work if no encoding options available
return # but we don't want crash, so that we can inform user
widgets.encoding_panel.encoding_selector.widget.set_active(0)
if movie_name_too == True:
widgets.file_panel.movie_name.set_text("movie")
widgets.file_panel.out_folder.set_current_folder(os.path.expanduser("~") + "/")
widgets.args_panel.use_args_check.set_active(False)
widgets.profile_panel.use_project_profile_check.set_active(True)
def enable_user_rendering(value):
widgets.encoding_panel.set_sensitive(value)
widgets.profile_panel.set_sensitive(value)
widgets.info_panel.set_sensitive(value)
widgets.args_panel.set_sensitive(value)
def set_render_gui():
progress_window.status_label.set_text(_("<b>Output File: </b>") + get_file_path())
progress_window.status_label.set_use_markup(True)
progress_window.remaining_time_label.set_text(_("<b>Estimated time left: </b>"))
progress_window.remaining_time_label.set_use_markup(True)
progress_window.passed_time_label.set_text(_("<b>Render time: </b>"))
progress_window.passed_time_label.set_use_markup(True)
progress_window.progress_bar.set_text("0%")
def save_render_start_time():
global render_start_time
render_start_time = time.time()
def set_render_progress_gui(fraction):
progress_window.progress_bar.set_fraction(fraction)
pros = int(fraction * 100)
progress_window.progress_bar.set_text(str(pros) + "%")
try:
passed_time = time.time() - render_start_time
full_time_est = (1.0 / fraction) * passed_time
passed_str = utils.get_time_str_for_sec_float(passed_time)
progress_window.passed_time_label.set_text(_("<b>Render Time: </b>") + passed_str)
progress_window.passed_time_label.set_use_markup(True)
if pros > 0.99: # Only start giving estimations after rendering has gone on for a while.
left_est = full_time_est - passed_time
left_str = utils.get_time_str_for_sec_float(left_est)
progress_window.remaining_time_label.set_text(_("<b>Estimated Time Left: </b>") + left_str)
progress_window.remaining_time_label.set_use_markup(True)
except: # A fraction of 0 usually gets sent here at beginning of rendering
pass
def exit_render_gui():
if aborted == True:
print "render aborted"
return
global progress_window
set_render_progress_gui(1.0)
passed_time = time.time() - render_start_time
passed_str = utils.get_time_str_for_sec_float(passed_time)
print "render done, time: " + passed_str
progress_window.remaining_time_label.set_text(_("<b>Estimated Time Left: </b>"))
progress_window.remaining_time_label.set_use_markup(True)
progress_window.passed_time_label.set_text(_("<b>Render Time: </b>") + passed_str)
progress_window.passed_time_label.set_use_markup(True)
progress_window.progress_bar.set_text(_("Render Complete!"))
dialogutils.delay_destroy_window(progress_window, 2.0)
progress_window = None
def maybe_open_rendered_file_in_bin():
if widgets.args_panel.open_in_bin.get_active() == False:
return
file_path = get_file_path()
open_media_file_callback(file_path)
def get_current_profile():
profile_index = widgets.profile_panel.out_profile_combo.widget.get_active()
if profile_index == 0:
# project_profile is first selection in combo box
profile = PROJECT().profile
else:
profile = mltprofiles.get_profile_for_index(profile_index - 1)
return profile
def fill_out_profile_widgets():
"""
Called some time after widget creation when current_sequence is known and these can be filled.
"""
widgets.profile_panel.out_profile_combo.fill_options()
_fill_info_box(current_sequence().profile)
def reload_profiles():
renderconsumer.load_render_profiles()
fill_out_profile_widgets()
def _render_type_changed():
if widgets.render_type_panel.type_combo.get_active() == 0: # User Defined
enable_user_rendering(True)
set_default_values_for_widgets()
widgets.render_type_panel.presets_selector.widget.set_sensitive(False)
_preset_selection_changed()
widgets.encoding_panel.encoding_selector.encoding_selection_changed()
else: # Preset Encodings
enable_user_rendering(False)
widgets.render_type_panel.presets_selector.widget.set_sensitive(True)
_preset_selection_changed()
widgets.args_panel.opts_save_button.set_sensitive(False)
widgets.args_panel.opts_load_button.set_sensitive(False)
widgets.args_panel.load_selection_button.set_sensitive(False)
widgets.args_panel.opts_view.set_sensitive(False)
widgets.args_panel.opts_view.get_buffer().set_text("")
def _out_profile_changed():
selected_index = widgets.profile_panel.out_profile_combo.widget.get_active()
if selected_index == 0:
_fill_info_box(current_sequence().profile)
else:
profile = mltprofiles.get_profile_for_index(selected_index - 1)
_fill_info_box(profile)
def _fill_info_box(profile):
info_panel = guicomponents.get_profile_info_small_box(profile)
widgets.info_panel = info_panel
widgets.profile_panel.out_profile_info_box.display_info(info_panel)
def _preset_selection_changed():
enc_index = widgets.render_type_panel.presets_selector.widget.get_active()
ext = renderconsumer.non_user_encodings[enc_index].extension
widgets.file_panel.extension_label.set_text("." + ext)
def _display_selection_in_opts_view():
profile = get_current_profile()
widgets.args_panel.display_encoding_args(profile,
widgets.encoding_panel.encoding_selector.widget.get_active(),
widgets.encoding_panel.quality_selector.widget.get_active())
def _save_opts_pressed():
rendergui.save_ffmpeg_opts_dialog(_save_opts_dialog_callback, FFMPEG_OPTS_SAVE_FILE_EXTENSION)
def _save_opts_dialog_callback(dialog, response_id):
if response_id == gtk.RESPONSE_ACCEPT:
file_path = dialog.get_filenames()[0]
opts_file = open(file_path, "w")
buf = widgets.args_panel.opts_view.get_buffer()
opts_text = buf.get_text(buf.get_start_iter(), buf.get_end_iter(), include_hidden_chars=True)
opts_file.write(opts_text)
opts_file.close()
dialog.destroy()
else:
dialog.destroy()
def _load_opts_pressed():
rendergui.load_ffmpeg_opts_dialog(_load_opts_dialog_callback, FFMPEG_OPTS_SAVE_FILE_EXTENSION)
def _load_opts_dialog_callback(dialog, response_id):
if response_id == gtk.RESPONSE_ACCEPT:
filename = dialog.get_filenames()[0]
args_file = open(filename)
args_text = args_file.read()
widgets.args_panel.opts_view.get_buffer().set_text(args_text)
dialog.destroy()
else:
dialog.destroy()
# ------------------------------------------------------------- framebuffer clip rendering
# Rendering a slow/fast motion version of media file.
def render_frame_buffer_clip(media_file):
rendergui.show_slowmo_dialog(media_file, _render_frame_buffer_clip_dialog_callback)
def _render_frame_buffer_clip_dialog_callback(dialog, response_id, fb_widgets, media_file):
if response_id == gtk.RESPONSE_ACCEPT:
# speed, filename folder
speed = float(int(fb_widgets.hslider.get_value())) / 100.0
file_name = fb_widgets.file_name.get_text()
filenames = fb_widgets.out_folder.get_filenames()
folder = filenames[0]
write_file = folder + "/"+ file_name + fb_widgets.extension_label.get_text()
if os.path.exists(write_file):
primary_txt = _("A File with given path exists!")
secondary_txt = _("It is not allowed to render Motion Files with same paths as existing files.\nSelect another name for file.")
dialogutils.warning_message(primary_txt, secondary_txt, dialog)
return
# Profile
profile_index = fb_widgets.out_profile_combo.get_active()
if profile_index == 0:
# project_profile is first selection in combo box
profile = PROJECT().profile
else:
profile = mltprofiles.get_profile_for_index(profile_index - 1)
# Render consumer properties
encoding_option_index = fb_widgets.encodings_cb.get_active()
quality_option_index = fb_widgets.quality_cb.get_active()
# Range
range_selection = fb_widgets.render_range.get_active()
dialog.destroy()
# Create motion producer
fr_path = "framebuffer:" + media_file.path + "?" + str(speed)
motion_producer = mlt.Producer(profile, None, str(fr_path))
mltrefhold.hold_ref(motion_producer)
# Create sequence and add motion producer into it
seq = sequence.Sequence(profile)
seq.create_default_tracks()
track = seq.tracks[seq.first_video_index]
track.append(motion_producer, 0, motion_producer.get_length() - 1)
print "motion clip render starting..."
consumer = renderconsumer.get_render_consumer_for_encoding_and_quality(write_file, profile, encoding_option_index, quality_option_index)
# start and end frames
start_frame = 0
end_frame = motion_producer.get_length() - 1
wait_for_producer_stop = True
if range_selection == 1:
start_frame = int(float(media_file.mark_in) * (1.0 / speed))
end_frame = int(float(media_file.mark_out + 1) * (1.0 / speed)) + int(1.0 / speed) #+ 40 # I'm unable to get this frame perfect.
# +40 is to make sure rendering stops after mark out.
if end_frame > motion_producer.get_length() - 1:
end_frame = motion_producer.get_length() - 1
wait_for_producer_stop = False # consumer wont stop automatically and needs to stopped explicitly
# Launch render
global motion_renderer, motion_progress_update
motion_renderer = renderconsumer.FileRenderPlayer(write_file, seq.tractor, consumer, start_frame, end_frame)
motion_renderer.wait_for_producer_end_stop = wait_for_producer_stop
motion_renderer.start()
title = _("Rendering Motion Clip")
text = "<b>Motion Clip File: </b>" + write_file
progress_bar = gtk.ProgressBar()
dialog = rendergui.clip_render_progress_dialog(_FB_render_stop, title, text, progress_bar, gui.editor_window.window)
motion_progress_update = renderconsumer.ProgressWindowThread(dialog, progress_bar, motion_renderer, _FB_render_stop)
motion_progress_update.start()
else:
dialog.destroy()
def _FB_render_stop(dialog, response_id):
print "motion clip render done"
global motion_renderer, motion_progress_update
motion_renderer.running = False
motion_progress_update.running = False
open_media_file_callback(motion_renderer.file_name)
motion_renderer.running = None
motion_progress_update.running = None
dialogutils.delay_destroy_window(dialog, 1.6)
# ----------------------------------------------------------------------- single track transition render
def render_single_track_transition_clip(transition_producer, encoding_option_index, quality_option_index, file_ext, transition_render_complete_cb, window_text):
# Set render complete callback to availble render stop callback using global variable
global transition_render_done_callback
transition_render_done_callback = transition_render_complete_cb
# Profile
profile = PROJECT().profile
folder = editorpersistance.prefs.render_folder
file_name = md5.new(str(os.urandom(32))).hexdigest()
write_file = folder + "/"+ file_name + file_ext
# Render consumer
consumer = renderconsumer.get_render_consumer_for_encoding_and_quality(write_file, profile, encoding_option_index, quality_option_index)
# start and end frames
start_frame = 0
end_frame = transition_producer.get_length() - 1
# Launch render
# TODO: fix naming this isn't motion renderer
global motion_renderer, motion_progress_update
motion_renderer = renderconsumer.FileRenderPlayer(write_file, transition_producer, consumer, start_frame, end_frame)
motion_renderer.start()
title = _("Rendering Transition Clip")
progress_bar = gtk.ProgressBar()
dialog = rendergui.clip_render_progress_dialog(_transition_render_stop, title, window_text, progress_bar, gui.editor_window.window)
motion_progress_update = renderconsumer.ProgressWindowThread(dialog, progress_bar, motion_renderer, _transition_render_stop)
motion_progress_update.start()
def _transition_render_stop(dialog, response_id):
global motion_renderer, motion_progress_update
motion_renderer.running = False
motion_progress_update.running = False
motion_renderer.running = None
motion_progress_update.running = None
transition_render_done_callback(motion_renderer.file_name)
dialogutils.delay_destroy_window(dialog, 1.0)
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
import app
import timeit
import edit
import utils
import persistance
import projectdata
import editorwindow
import mltplayer
import mltprofiles
import sequence
import updater
import mlt
import os
value = 0
def buildProject(project):
app.project = project
sequence = project.c_seq
edit.set_edit_context(sequence)
project.add_unnamed_bin()
track = sequence.tracks[1]
track2 = sequence.tracks[2]
media_file1 = project.media_files[1]
media_file2 = project.media_files[2]
media_file3 = project.media_files[3]
media_file4 = project.media_files[4]
clip1 = sequence.create_file_producer_clip(media_file1.path)
data1 = {"track": track,
"clip":clip1,
"clip_in":30,
"clip_out":30}
action1 = edit.append_action(data1)
action1.do_edit()
for i in range(0, 3):
clip2 = sequence.create_file_producer_clip(media_file2.path)
data2 = {"track": track,
"clip":clip2,
"clip_in":30,
"clip_out":90}
action2 = edit.append_action(data2)
action2.do_edit()
clip12 = sequence.create_file_producer_clip(media_file4.path)
data12 = {"track": track,
"clip":clip12,
"clip_in":10,
"clip_out":30}
action12 = edit.append_action(data12)
action12.do_edit()
print track.count()
def load_save(project, path):
persistance.save_project(project, path)
return persistance.load_project(path)
def load_clips(project):
clip_path = "/home/janne/test/clipit/sekalaista"
count = 9;
file_list = os.listdir(clip_path)
if len(file_list) < count:
count = len(file_list)
for i in range(count):
file_path = clip_path + "/" + file_list[i]
print file_path
project.add_media_file(file_path)
def get_render_options_test():
# Create render options object
render_options = {}
render_options["file_path"] = "/home/janne/test/pyrender.mp4"
render_options["render_type"] = "VIDEO_AUDIO"
render_options["f"] = "mp4" # format
render_options["vcodec"] = "mpeg4" # vidoe codec
render_options["b"] = "2500k" # video bitrate
render_options["acodec"] = "libmp3lame" # audion codec
render_options["ar"] = "44100" # audio sampling frequency
render_options["ac"] = "2" # number of audio channels
render_options["ab"] = "128k"
return render_options
def get_seq_render_options_test():
render_options = {}
render_options["render_type"] = "IMAGE_SEQUENCE"
render_options["vcodec"] = "png" # vidoe codec
render_options["file_path"] = "/home/janne/test/rend/frame_%d.png"
return render_options
"""
"""
typedef struct
{
int clip; /**< the index of the clip within the playlist */
mlt_producer producer; /**< the clip's producer (or parent producer of a cut) */
mlt_producer cut; /**< the clips' cut producer */
mlt_position start; /**< the time this begins relative to the beginning of the playlist */
char *resource; /**< the file name or address of the clip */
mlt_position frame_in; /**< the clip's in point */
mlt_position frame_out; /**< the clip's out point */
mlt_position frame_count; /**< the duration of the clip */
mlt_position length; /**< the unedited duration of the clip */
float fps; /**< the frame rate of the clip */
int repeat; /**< the number of times the clip is repeated */
}
mlt_playlist_clip_info;
"""
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
import pygtk
pygtk.require('2.0');
import gtk
import mlt
import os
import threading
import time
import app
import appconsts
import dialogs
import dialogutils
import editorpersistance
import editorstate
import gui
import guiutils
import mltrefhold
import persistance
import renderconsumer
import sequence
import utils
manager_window = None
progress_window = None
proxy_render_issues_window = None
render_thread = None
runner_thread = None
load_thread = None
# These are made to correspond with size selector combobox indexes on manager window
PROXY_SIZE_FULL = 0
PROXY_SIZE_HALF = 1
PROXY_SIZE_QUARTER = 2
class ProxyRenderRunnerThread(threading.Thread):
def __init__(self, proxy_profile, files_to_render, set_as_proxy_immediately):
threading.Thread.__init__(self)
self.proxy_profile = proxy_profile
self.files_to_render = files_to_render
self.set_as_proxy_immediately = set_as_proxy_immediately
self.aborted = False
def run(self):
items = 1
global progress_window
start = time.time()
elapsed = 0
proxy_w, proxy_h = _get_proxy_dimensions(self.proxy_profile, editorstate.PROJECT().proxy_data.size)
proxy_encoding = _get_proxy_encoding()
self.current_render_file_path = None
print "proxy render started, items: " + str(len(self.files_to_render)) + ", dim: " + str(proxy_w) + "x" + str(proxy_h)
for media_file in self.files_to_render:
if self.aborted == True:
break
# Create render objects
proxy_file_path = media_file.create_proxy_path(proxy_w, proxy_h, proxy_encoding.extension)
self.current_render_file_path = proxy_file_path
consumer = renderconsumer.get_render_consumer_for_encoding(
proxy_file_path,
self.proxy_profile,
proxy_encoding)
# Bit rates for proxy files are counted using 2500kbs for
# PAL size image as starting point.
pal_pix_count = 720.0 * 576.0
pal_proxy_rate = 2500.0
proxy_pix_count = float(proxy_w * proxy_h)
proxy_rate = pal_proxy_rate * (proxy_pix_count / pal_pix_count)
proxy_rate = int(proxy_rate / 100) * 100 # Make proxy rate even hundred
# There are no practical reasons to have bitrates lower than 500kbs.
if proxy_rate < 500:
proxy_rate = 500
consumer.set("vb", str(int(proxy_rate)) + "k")
consumer.set("rescale", "nearest")
file_producer = mlt.Producer(self.proxy_profile, str(media_file.path))
mltrefhold.hold_ref(file_producer)
stop_frame = file_producer.get_length() - 1
# Create and launch render thread
global render_thread
render_thread = renderconsumer.FileRenderPlayer(None, file_producer, consumer, 0, stop_frame)
render_thread.start()
# Render view update loop
self.thread_running = True
self.aborted = False
while self.thread_running:
if self.aborted == True:
break
render_fraction = render_thread.get_render_fraction()
now = time.time()
elapsed = now - start
gtk.gdk.threads_enter()
progress_window.update_render_progress(render_fraction, media_file.name, items, len(self.files_to_render), elapsed)
gtk.gdk.threads_leave()
render_thread.producer.get_length()
if render_thread.producer.frame() >= stop_frame:
self.thread_running = False
media_file.add_proxy_file(proxy_file_path)
if self.set_as_proxy_immediately: # When proxy mode is USE_PROXY_MEDIA all proxy files are used all the time
media_file.set_as_proxy_media_file()
self.current_render_file_path = None
else:
time.sleep(0.1)
if not self.aborted:
items = items + 1
gtk.gdk.threads_enter()
progress_window.update_render_progress(0, media_file.name, items, len(self.files_to_render), elapsed)
gtk.gdk.threads_leave()
else:
print "proxy render aborted"
render_thread.shutdown()
break
render_thread.shutdown()
gtk.gdk.threads_enter()
_proxy_render_stopped()
gtk.gdk.threads_leave()
# Remove unfinished proxy files
if self.current_render_file_path != None:
os.remove(self.current_render_file_path)
# If we're currently proxy editing, we need to update
# all the clips on the timeline to use proxy media.
if editorstate.PROJECT().proxy_data.proxy_mode == appconsts.USE_PROXY_MEDIA:
_auto_renconvert_after_proxy_render_in_proxy_mode()
print "proxy render done"
def abort(self):
render_thread.shutdown()
self.aborted = True
self.thread_running = False
class ProxyManagerDialog:
def __init__(self):
self.dialog = gtk.Dialog(_("Proxy Manager"), None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(_("Close Manager").encode('utf-8'), gtk.RESPONSE_CLOSE))
# Encoding
self.enc_select = gtk.combo_box_new_text()
encodings = renderconsumer.proxy_encodings
if len(encodings) < 1: # no encoding options available, system does not have right codecs
# display info
pass
for encoption in encodings:
self.enc_select.append_text(encoption.name)
current_enc = editorstate.PROJECT().proxy_data.encoding
if current_enc >= len(encodings): # current encoding selection not available
current_enc = 0
editorstate.PROJECT().proxy_data.encoding = 0
self.enc_select.set_active(current_enc)
self.enc_select.connect("changed",
lambda w,e: self.encoding_changed(w.get_active()),
None)
self.size_select = gtk.combo_box_new_text()
self.size_select.append_text(_("Project Image Size"))
self.size_select.append_text(_("Half Project Image Size"))
self.size_select.append_text(_("Quarter Project Image Size"))
self.size_select.set_active(editorstate.PROJECT().proxy_data.size)
self.size_select.connect("changed",
lambda w,e: self.size_changed(w.get_active()),
None)
row_enc = gtk.HBox(False, 2)
row_enc.pack_start(gtk.Label(), True, True, 0)
row_enc.pack_start(self.enc_select, False, False, 0)
row_enc.pack_start(self.size_select, False, False, 0)
row_enc.pack_start(gtk.Label(), True, True, 0)
vbox_enc = gtk.VBox(False, 2)
vbox_enc.pack_start(row_enc, False, False, 0)
vbox_enc.pack_start(guiutils.pad_label(8, 12), False, False, 0)
panel_encoding = guiutils.get_named_frame(_("Proxy Encoding"), vbox_enc)
# Mode
media_files = editorstate.PROJECT().media_files
video_files = 0
proxy_files = 0
for k, media_file in media_files.iteritems():
if media_file.type == appconsts.VIDEO:
video_files = video_files + 1
if media_file.has_proxy_file == True or media_file.is_proxy_file == True:
proxy_files = proxy_files + 1
proxy_status_label = gtk.Label(_("Proxy Stats:"))
proxy_status_value = gtk.Label(str(proxy_files) + _(" proxy file(s) for ") + str(video_files) + _(" video file(s)"))
row_proxy_status = guiutils.get_two_column_box_right_pad(proxy_status_label, proxy_status_value, 150, 150)
proxy_mode_label = gtk.Label(_("Current Proxy Mode:"))
self.proxy_mode_value = gtk.Label()
self.set_mode_display_value()
row_proxy_mode = guiutils.get_two_column_box_right_pad(proxy_mode_label, self.proxy_mode_value, 150, 150)
self.convert_progress_bar = gtk.ProgressBar()
self.convert_progress_bar.set_text(_("Press Button to Change Mode"))
self.use_button = gtk.Button(_("Use Proxy Media"))
self.dont_use_button = gtk.Button(_("Use Original Media"))
self.set_convert_buttons_state()
self.use_button.connect("clicked", lambda w: _convert_to_proxy_project())
self.dont_use_button.connect("clicked", lambda w: _convert_to_original_media_project())
c_box_2 = gtk.HBox(True, 8)
c_box_2.pack_start(self.use_button, True, True, 0)
c_box_2.pack_start(self.dont_use_button, True, True, 0)
row2_onoff = gtk.HBox(False, 2)
row2_onoff.pack_start(gtk.Label(), True, True, 0)
row2_onoff.pack_start(c_box_2, False, False, 0)
row2_onoff.pack_start(gtk.Label(), True, True, 0)
vbox_onoff = gtk.VBox(False, 2)
vbox_onoff.pack_start(row_proxy_status, False, False, 0)
vbox_onoff.pack_start(row_proxy_mode, False, False, 0)
vbox_onoff.pack_start(guiutils.pad_label(12, 12), False, False, 0)
vbox_onoff.pack_start(self.convert_progress_bar, False, False, 0)
vbox_onoff.pack_start(row2_onoff, False, False, 0)
panel_onoff = guiutils.get_named_frame(_("Project Proxy Mode"), vbox_onoff)
# Pane
vbox = gtk.VBox(False, 2)
vbox.pack_start(panel_encoding, False, False, 0)
vbox.pack_start(panel_onoff, False, False, 0)
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(12, 12, 12, 12)
alignment.add(vbox)
self.dialog.vbox.pack_start(alignment, True, True, 0)
dialogutils.default_behaviour(self.dialog)
self.dialog.connect('response', dialogutils.dialog_destroy)
self.dialog.show_all()
def set_convert_buttons_state(self):
proxy_mode = editorstate.PROJECT().proxy_data.proxy_mode
if proxy_mode == appconsts.USE_PROXY_MEDIA:
self.use_button.set_sensitive(False)
self.dont_use_button.set_sensitive(True)
else:
self.use_button.set_sensitive(True)
self.dont_use_button.set_sensitive(False)
def set_mode_display_value(self):
if editorstate.PROJECT().proxy_data.proxy_mode == appconsts.USE_PROXY_MEDIA:
mode_str = _("Using Proxy Media")
else:
mode_str = _("Using Original Media")
self.proxy_mode_value.set_text(mode_str)
def encoding_changed(self, enc_index):
editorstate.PROJECT().proxy_data.encoding = enc_index
def size_changed(self, size_index):
editorstate.PROJECT().proxy_data.size = size_index
def update_proxy_mode_display(self):
self.set_convert_buttons_state()
self.set_mode_display_value()
self.convert_progress_bar.set_text(_("Press Button to Change Mode"))
self.convert_progress_bar.set_fraction(0.0)
class ProxyRenderProgressDialog:
def __init__(self):
self.dialog = gtk.Dialog(_("Creating Proxy Files"),
gui.editor_window.window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(_("Stop").encode('utf-8'), gtk.RESPONSE_REJECT))
self.render_progress_bar = gtk.ProgressBar()
self.render_progress_bar.set_text("0 %")
prog_align = gtk.Alignment(0.5, 0.5, 1.0, 0.0)
prog_align.set_padding(0, 0, 0, 0)
prog_align.add(self.render_progress_bar)
prog_align.set_size_request(550, 30)
self.elapsed_value = gtk.Label()
self.current_render_value = gtk.Label()
self.items_value = gtk.Label()
est_label = guiutils.get_right_justified_box([guiutils.bold_label(_("Elapsed:"))])
current_label = guiutils.get_right_justified_box([guiutils.bold_label(_("Current Media File:"))])
items_label = guiutils.get_right_justified_box([guiutils.bold_label(_("Rendering Item:"))])
est_label.set_size_request(250, 20)
current_label.set_size_request(250, 20)
items_label.set_size_request(250, 20)
info_vbox = gtk.VBox(False, 0)
info_vbox.pack_start(guiutils.get_left_justified_box([est_label, self.elapsed_value]), False, False, 0)
info_vbox.pack_start(guiutils.get_left_justified_box([current_label, self.current_render_value]), False, False, 0)
info_vbox.pack_start(guiutils.get_left_justified_box([items_label, self.items_value]), False, False, 0)
progress_vbox = gtk.VBox(False, 2)
progress_vbox.pack_start(info_vbox, False, False, 0)
progress_vbox.pack_start(guiutils.get_pad_label(10, 8), False, False, 0)
progress_vbox.pack_start(prog_align, False, False, 0)
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(12, 12, 12, 12)
alignment.add(progress_vbox)
alignment.show_all()
self.dialog.vbox.pack_start(alignment, True, True, 0)
self.dialog.set_has_separator(False)
self.dialog.connect('response', self.stop_pressed)
self.dialog.show()
def update_render_progress(self, fraction, media_file_name, current_item, items, elapsed):
elapsed_str= " " + utils.get_time_str_for_sec_float(elapsed)
self.elapsed_value .set_text(elapsed_str)
self.current_render_value.set_text(" " + media_file_name)
self.items_value.set_text( " " + str(current_item) + "/" + str(items))
self.render_progress_bar.set_fraction(fraction)
self.render_progress_bar.set_text(str(int(fraction * 100)) + " %")
def stop_pressed(self, dialog, response_id):
global runner_thread
runner_thread.abort()
class ProxyRenderIssuesWindow:
def __init__(self, files_to_render, already_have_proxies, not_video_files, is_proxy_file,
other_project_proxies, proxy_w, proxy_h, proxy_file_extension):
dialog_title =_("Proxy Render Info")
self.files_to_render = files_to_render
self.other_project_proxies = other_project_proxies
self.already_have_proxies = already_have_proxies
self.proxy_w = proxy_w
self.proxy_h = proxy_h
self.proxy_file_extension = proxy_file_extension
self.issues = 1
if (len(files_to_render) + len(already_have_proxies) + len(other_project_proxies)) == 0 and not_video_files > 0:
self.dialog = gtk.Dialog(dialog_title,
gui.editor_window.window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(_("Close").encode('utf-8'), gtk.RESPONSE_CLOSE))
info_box = dialogutils.get_warning_message_dialog_panel(_("Nothing will be rendered"),
_("No video files were selected.\nOnly video files can have proxy files."),
True)
self.dialog.connect('response', dialogutils.dialog_destroy)
else:
self.dialog = gtk.Dialog(dialog_title,
gui.editor_window.window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(_("Cancel").encode('utf-8'), gtk.RESPONSE_CANCEL,
_("Do Render Action" ).encode('utf-8'), gtk.RESPONSE_OK))
self.dialog.connect('response', self.response)
rows = ""
if len(already_have_proxies) > 0 and len(other_project_proxies) > 0:
text = _("Proxies exist that were created by this and other projects for ") + str(len(already_have_proxies) + len(other_project_proxies)) + _(" file(s).\n")
rows = rows + self.issues_str() + text
elif len(already_have_proxies) > 0 and len(other_project_proxies) == 0:
text = _("Proxies have already been created for ") + str(len(already_have_proxies)) + _(" file(s).\n")
rows = rows + self.issues_str() + text
elif len(other_project_proxies) > 0:
text = _("Proxies exist that were created by other projects for ") + str(len(other_project_proxies)) + _(" file(s).\n")
rows = rows + self.issues_str() + text
if not_video_files > 0:
text = _("You are trying to create proxies for ") + str(not_video_files) + _(" non-video file(s).\n")
rows = rows + self.issues_str() + text
if is_proxy_file > 0:
text = _("You are trying to create proxies for ") + str(not_video_files) + _(" proxy file(s).\n")
rows = rows + self.issues_str() + text
issues_box = dialogutils.get_warning_message_dialog_panel("There are some issues with proxy render request",
rows,
True)
self.action_select = gtk.combo_box_new_text()
self.action_select.append_text(_("Render Unrendered Possible & Use existing"))
self.action_select.append_text(_("Rerender All Possible" ))
self.action_select.set_active(0)
action_row = guiutils.get_left_justified_box([guiutils.get_pad_label(24, 10), gtk.Label(_("Select Render Action: ")), self.action_select])
info_box = gtk.VBox()
info_box.pack_start(issues_box, False, False, 0)
info_box.pack_start(action_row, False, False, 0)
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
alignment.set_padding(0, 0, 0, 0)
alignment.add(info_box)
alignment.show_all()
self.dialog.vbox.pack_start(alignment, True, True, 0)
self.dialog.set_has_separator(False)
self.dialog.show()
def issues_str(self):
issue_str = str(self.issues) + ") "
self.issues = self.issues + 1
return issue_str
def response(self, dialog, response_id):
if response_id == gtk.RESPONSE_CANCEL:
dialog.destroy()
else:
if self.action_select.get_active() == 0: # Render Unrendered Possible & Use existing
for f in self.other_project_proxies:
f.add_existing_proxy_file(self.proxy_w, self.proxy_h, self.proxy_file_extension)
if editorstate.PROJECT().proxy_data.proxy_mode == appconsts.USE_PROXY_MEDIA:
f.set_as_proxy_media_file()
else: # Rerender All Possible
# We can't mess existing proxy files that are used by other projects
_set_media_files_to_use_unique_proxies(self.other_project_proxies)
_set_media_files_to_use_unique_proxies(self.already_have_proxies)
# Add to files being rendered
self.files_to_render.extend(self.other_project_proxies)
self.files_to_render.extend(self.already_have_proxies)
dialog.destroy()
global proxy_render_issues_window
proxy_render_issues_window = None
_create_proxy_files(self.files_to_render)
# ------------------------------------------------------------- event interface
def show_proxy_manager_dialog():
global manager_window
manager_window = ProxyManagerDialog()
def set_menu_to_proxy_state():
if editorstate.PROJECT().proxy_data.proxy_mode == appconsts.USE_ORIGINAL_MEDIA:
gui.editor_window.uimanager.get_widget('/MenuBar/FileMenu/SaveSnapshot').set_sensitive(True)
else:
gui.editor_window.uimanager.get_widget('/MenuBar/FileMenu/SaveSnapshot').set_sensitive(False)
def create_proxy_files_pressed():
media_file_widgets = gui.media_list_view.get_selected_media_objects()
if len(media_file_widgets) == 0:
return
media_files = []
for w in media_file_widgets:
media_files.append(w.media_file)
_do_create_proxy_files(media_files)
def create_proxy_menu_item_selected(media_file):
media_files = []
media_files.append(media_file)
_do_create_proxy_files(media_files)
def _do_create_proxy_files(media_files, retry_from_render_folder_select=False):
if editorpersistance.prefs.render_folder == None:
if retry_from_render_folder_select == True:
return
dialogs.select_rendred_clips_dir(_create_proxy_render_folder_select_callback,
gui.editor_window.window, editorpersistance.prefs.render_folder,
media_files)
return
# Create proxies dir if does not exist
proxies_dir = _get_proxies_dir()
if not os.path.exists(proxies_dir):
os.mkdir(proxies_dir)
proxy_profile = _get_proxy_profile(editorstate.PROJECT())
proxy_w, proxy_h = _get_proxy_dimensions(proxy_profile, editorstate.PROJECT().proxy_data.size)
proxy_file_extension = _get_proxy_encoding().extension
files_to_render = []
not_video_files = 0
already_have_proxies = []
is_proxy_file = 0
other_project_proxies = []
for f in media_files:
#f = w.media_file
if f.is_proxy_file == True: # Can't create a proxy file for a proxy file
is_proxy_file = is_proxy_file + 1
continue
if f.type != appconsts.VIDEO: # only video files can have proxy files
not_video_files = not_video_files + 1
continue
if f.has_proxy_file == True: # no need to to create proxy files again, unless forced by user
if os.path.exists(f.second_file_path):
already_have_proxies.append(f)
continue
path_for_size_and_encoding = f.create_proxy_path(proxy_w, proxy_h, proxy_file_extension)
if os.path.exists(path_for_size_and_encoding): # A proxy for media file has been created by other projects. Get user to confirm overwrite
other_project_proxies.append(f)
continue
files_to_render.append(f)
if len(already_have_proxies) > 0 or len(other_project_proxies) > 0 or not_video_files > 0 or is_proxy_file > 0 or len(files_to_render) == 0:
global proxy_render_issues_window
proxy_render_issues_window = ProxyRenderIssuesWindow(files_to_render, already_have_proxies,
not_video_files, is_proxy_file, other_project_proxies,
proxy_w, proxy_h, proxy_file_extension)
return
_create_proxy_files(files_to_render)
def _set_media_files_to_use_unique_proxies(media_files_list):
for media_file in media_files_list:
media_file.use_unique_proxy = True
def _create_proxy_files(media_files_to_render):
proxy_profile = _get_proxy_profile(editorstate.PROJECT())
if editorstate.PROJECT().proxy_data.proxy_mode == appconsts.USE_ORIGINAL_MEDIA:
set_as_proxy_immediately = False
else:
set_as_proxy_immediately = True
global progress_window, runner_thread
progress_window = ProxyRenderProgressDialog()
runner_thread = ProxyRenderRunnerThread(proxy_profile, media_files_to_render, set_as_proxy_immediately)
runner_thread.start()
# ------------------------------------------------------------------ module functions
def _get_proxies_dir():
return editorpersistance.prefs.render_folder + "/proxies"
def _get_proxy_encoding():
enc_index = editorstate.PROJECT().proxy_data.encoding
return renderconsumer.proxy_encodings[enc_index]
def _get_proxy_dimensions(project_profile, proxy_size):
# Get new dimension that are about half of previous and diviseble by eight
if proxy_size == PROXY_SIZE_FULL:
size_mult = 1.0
elif proxy_size == PROXY_SIZE_HALF:
size_mult = 0.5
else: # quarter size
size_mult = 0.25
old_width_half = int(project_profile.width() * size_mult)
old_height_half = int(project_profile.height() * size_mult)
new_width = old_width_half - old_width_half % 8
new_height = old_height_half - old_height_half % 8
return (new_width, new_height)
def _get_proxy_profile(project):
project_profile = project.profile
new_width, new_height = _get_proxy_dimensions(project_profile, project.proxy_data.size)
file_contents = "description=" + "proxy render profile" + "\n"
file_contents += "frame_rate_num=" + str(project_profile.frame_rate_num()) + "\n"
file_contents += "frame_rate_den=" + str(project_profile.frame_rate_den()) + "\n"
file_contents += "width=" + str(new_width) + "\n"
file_contents += "height=" + str(new_height) + "\n"
file_contents += "progressive=1" + "\n"
file_contents += "sample_aspect_num=" + str(project_profile.sample_aspect_num()) + "\n"
file_contents += "sample_aspect_den=" + str(project_profile.sample_aspect_den()) + "\n"
file_contents += "display_aspect_num=" + str(project_profile.display_aspect_num()) + "\n"
file_contents += "display_aspect_den=" + str(project_profile.display_aspect_den()) + "\n"
proxy_profile_path = utils.get_hidden_user_dir_path() + "temp_proxy_profile"
profile_file = open(proxy_profile_path, "w")
profile_file.write(file_contents)
profile_file.close()
proxy_profile = mlt.Profile(proxy_profile_path)
return proxy_profile
def _proxy_render_stopped():
global progress_window, runner_thread
progress_window.dialog.destroy()
gui.media_list_view.widget.queue_draw()
progress_window = None
runner_thread = None
def _create_proxy_render_folder_select_callback(dialog, response_id, file_select, media_files):
try:
folder = file_select.get_filenames()[0]
except:
dialog.destroy()
return
dialog.destroy()
if response_id == gtk.RESPONSE_YES:
if folder == os.path.expanduser("~"):
dialogs.rendered_clips_no_home_folder_dialog()
else:
editorpersistance.prefs.render_folder = folder
editorpersistance.save()
_do_create_proxy_files(media_files, True)
# ----------------------------------------------------------- changing proxy modes
def _convert_to_proxy_project():
editorstate.PROJECT().proxy_data.proxy_mode = appconsts.CONVERTING_TO_USE_PROXY_MEDIA
conv_temp_project_path = utils.get_hidden_user_dir_path() + "proxy_conv.flb"
manager_window.convert_progress_bar.set_text(_("Converting Project to Use Proxy Media"))
persistance.save_project(editorstate.PROJECT(), conv_temp_project_path)
global load_thread
load_thread = ProxyProjectLoadThread(conv_temp_project_path, manager_window.convert_progress_bar)
load_thread.start()
def _convert_to_original_media_project():
editorstate.PROJECT().proxy_data.proxy_mode = appconsts.CONVERTING_TO_USE_ORIGINAL_MEDIA
conv_temp_project_path = utils.get_hidden_user_dir_path() + "proxy_conv.flb"
manager_window.convert_progress_bar.set_text(_("Converting to Use Original Media"))
persistance.save_project(editorstate.PROJECT(), conv_temp_project_path)
global load_thread
load_thread = ProxyProjectLoadThread(conv_temp_project_path, manager_window.convert_progress_bar)
load_thread.start()
def _auto_renconvert_after_proxy_render_in_proxy_mode():
# Save to temp to convert to using original media
project = editorstate.PROJECT()
project.proxy_data.proxy_mode = appconsts.CONVERTING_TO_USE_ORIGINAL_MEDIA
conv_temp_project_path = utils.get_hidden_user_dir_path() + "proxy_conv.flb"
persistance.save_project(editorstate.PROJECT(), conv_temp_project_path)
project.proxy_data.proxy_mode = appconsts.USE_ORIGINAL_MEDIA
# Load saved temp original media project
persistance.show_messages = False
project = persistance.load_project(conv_temp_project_path)
# Save to temp to convert back to using proxy media
project.proxy_data.proxy_mode = appconsts.CONVERTING_TO_USE_PROXY_MEDIA
persistance.save_project(project, conv_temp_project_path)
project.proxy_data.proxy_mode = appconsts.USE_PROXY_MEDIA
# Load saved temp proxy project
project = persistance.load_project(conv_temp_project_path)
# Open saved temp project
app.stop_autosave()
gtk.gdk.threads_enter()
app.open_project(project)
gtk.gdk.threads_leave()
app.start_autosave()
editorstate.update_current_proxy_paths()
persistance.show_messages = True
def _converting_proxy_mode_done():
global load_thread
load_thread = None
editorstate.update_current_proxy_paths()
manager_window.update_proxy_mode_display()
gui.media_list_view.widget.queue_draw()
gui.tline_left_corner.update_gui()
set_menu_to_proxy_state()
class ProxyProjectLoadThread(threading.Thread):
def __init__(self, proxy_project_path, progressbar):
threading.Thread.__init__(self)
self.proxy_project_path = proxy_project_path
self.progressbar = progressbar
def run(self):
pulse_runner = guiutils.PulseThread(self.progressbar)
pulse_runner.start()
time.sleep(2.0)
persistance.show_messages = False
try:
gtk.gdk.threads_enter()
project = persistance.load_project(self.proxy_project_path)
sequence.set_track_counts(project)
gtk.gdk.threads_leave()
except persistance.FileProducerNotFoundError as e:
print "did not find file:", e
pulse_runner.running = False
time.sleep(0.3) # need to be sure pulse_runner has stopped
app.stop_autosave()
gtk.gdk.threads_enter()
app.open_project(project)
gtk.gdk.threads_leave()
# Loaded project has been converted, set proxy mode to correct mode
if project.proxy_data.proxy_mode == appconsts.CONVERTING_TO_USE_PROXY_MEDIA:
project.proxy_data.proxy_mode = appconsts.USE_PROXY_MEDIA
else:
project.proxy_data.proxy_mode = appconsts.USE_ORIGINAL_MEDIA
app.start_autosave()
global load_thread
load_thread = None
persistance.show_messages = True
gtk.gdk.threads_enter()
_converting_proxy_mode_done()
gtk.gdk.threads_leave()
"""
class PulseThread(threading.Thread):
def __init__(self, proress_bar):
threading.Thread.__init__(self)
self.proress_bar = proress_bar
def run(self):
self.exited = False
self.running = True
while self.running:
gtk.gdk.threads_enter()
self.proress_bar.pulse()
gtk.gdk.threads_leave()
time.sleep(0.1)
self.exited = True
"""
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module contains classes and build methods to create GUI objects.
"""
import cairo
import gobject
import pygtk
pygtk.require('2.0');
import gtk
import math
import pango
import pangocairo
import appconsts
from cairoarea import CairoDrawableArea
import dnd
import editorpersistance
import editorstate
from editorstate import current_sequence
from editorstate import current_bin
from editorstate import PROJECT
from editorstate import PLAYER
import gui
import guiutils
import mltfilters
import mltprofiles
import mlttransitions
import respaths
import translations
import utils
SEPARATOR_HEIGHT = 5
SEPARATOR_WIDTH = 250
MONITOR_COMBO_WIDTH = 32
MONITOR_COMBO_HEIGHT = 12
MEDIA_OBJECT_WIDGET_WIDTH = 120
MEDIA_OBJECT_WIDGET_HEIGHT = 105
CLIP_EDITOR_LEFT_WIDTH = 200
TC_COLOR = (0.7, 0.7, 0.7)
BIG_TC_GRAD_STOPS = [ (1, 1, 1, 1, 0.2),
(0.8, 1, 1, 1, 0),
(0.51, 1, 1, 1, 0),
(0.50, 1, 1, 1, 0.25),
(0, 1, 1, 1, 0.4)]
BIG_TC_FRAME_GRAD_STOPS = [ (1, 0.7, 0.7, 0.7, 1),
(0.95, 0.7, 0.7, 0.7, 1),
(0.75, 0.1, 0.1, 0.1, 1),
(0, 0.14, 0.14, 0.14, 1)]
M_PI = math.pi
has_proxy_icon = None
is_proxy_icon = None
graphics_icon = None
imgseq_icon = None
audio_icon = None
pattern_icon = None
# ------------------------------------------------- item lists
class ImageTextTextListView(gtk.VBox):
"""
GUI component displaying list with columns: img, text, text
Middle column expands.
"""
def __init__(self):
gtk.VBox.__init__(self)
# Datamodel: icon, text, text
self.storemodel = gtk.ListStore(gtk.gdk.Pixbuf, str, str)
# Scroll container
self.scroll = gtk.ScrolledWindow()
self.scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
self.scroll.set_shadow_type(gtk.SHADOW_ETCHED_IN)
# View
self.treeview = gtk.TreeView(self.storemodel)
self.treeview.set_property("rules_hint", True)
self.treeview.set_headers_visible(False)
tree_sel = self.treeview.get_selection()
tree_sel.set_mode(gtk.SELECTION_SINGLE)
# Column views
self.icon_col = gtk.TreeViewColumn("Icon")
self.text_col_1 = gtk.TreeViewColumn("text1")
self.text_col_2 = gtk.TreeViewColumn("text2")
# Cell renderers
self.icon_rend = gtk.CellRendererPixbuf()
self.icon_rend.props.xpad = 6
self.text_rend_1 = gtk.CellRendererText()
self.text_rend_1.set_property("ellipsize", pango.ELLIPSIZE_END)
self.text_rend_2 = gtk.CellRendererText()
self.text_rend_2.set_property("yalign", 0.0)
# Build column views
self.icon_col.set_expand(False)
self.icon_col.set_spacing(5)
self.icon_col.pack_start(self.icon_rend)
self.icon_col.add_attribute(self.icon_rend, 'pixbuf', 0)
self.text_col_1.set_expand(True)
self.text_col_1.set_spacing(5)
self.text_col_1.set_sizing(gtk.TREE_VIEW_COLUMN_GROW_ONLY)
self.text_col_1.set_min_width(150)
self.text_col_1.pack_start(self.text_rend_1)
self.text_col_1.add_attribute(self.text_rend_1, "text", 1)
self.text_col_2.set_expand(False)
self.text_col_2.pack_start(self.text_rend_2)
self.text_col_2.add_attribute(self.text_rend_2, "text", 2)
# Add column views to view
self.treeview.append_column(self.icon_col)
self.treeview.append_column(self.text_col_1)
self.treeview.append_column(self.text_col_2)
# Build widget graph and display
self.scroll.add(self.treeview)
self.pack_start(self.scroll)
self.scroll.show_all()
def get_selected_rows_list(self):
model, rows = self.treeview.get_selection().get_selected_rows()
return rows
# ------------------------------------------------- item lists
class ImageTextImageListView(gtk.VBox):
"""
GUI component displaying list with columns: img, text, img
Middle column expands.
"""
def __init__(self):
gtk.VBox.__init__(self)
# Datamodel: icon, text, icon
self.storemodel = gtk.ListStore(gtk.gdk.Pixbuf, str, gtk.gdk.Pixbuf)
# Scroll container
self.scroll = gtk.ScrolledWindow()
self.scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
self.scroll.set_shadow_type(gtk.SHADOW_ETCHED_IN)
# View
self.treeview = gtk.TreeView(self.storemodel)
self.treeview.set_property("rules_hint", True)
self.treeview.set_headers_visible(False)
tree_sel = self.treeview.get_selection()
tree_sel.set_mode(gtk.SELECTION_SINGLE)
# Column views
self.icon_col_1 = gtk.TreeViewColumn("icon1")
self.text_col_1 = gtk.TreeViewColumn("text1")
self.icon_col_2 = gtk.TreeViewColumn("icon2")
# Cell renderers
self.icon_rend_1 = gtk.CellRendererPixbuf()
self.icon_rend_1.props.xpad = 6
self.text_rend_1 = gtk.CellRendererText()
self.text_rend_1.set_property("ellipsize", pango.ELLIPSIZE_END)
self.icon_rend_2 = gtk.CellRendererPixbuf()
self.icon_rend_2.props.xpad = 6
# Build column views
self.icon_col_1.set_expand(False)
self.icon_col_1.set_spacing(5)
self.icon_col_1.pack_start(self.icon_rend_1)
self.icon_col_1.add_attribute(self.icon_rend_1, 'pixbuf', 0)
self.text_col_1.set_expand(True)
self.text_col_1.set_spacing(5)
self.text_col_1.set_sizing(gtk.TREE_VIEW_COLUMN_GROW_ONLY)
self.text_col_1.set_min_width(150)
self.text_col_1.pack_start(self.text_rend_1)
self.text_col_1.add_attribute(self.text_rend_1, "text", 1)
self.icon_col_2.set_expand(False)
self.icon_col_2.set_spacing(5)
self.icon_col_2.pack_start(self.icon_rend_2)
self.icon_col_2.add_attribute(self.icon_rend_2, 'pixbuf', 2)
# Add column views to view
self.treeview.append_column(self.icon_col_1)
self.treeview.append_column(self.text_col_1)
self.treeview.append_column(self.icon_col_2)
# Build widget graph and display
self.scroll.add(self.treeview)
self.pack_start(self.scroll)
self.scroll.show_all()
def get_selected_rows_list(self):
model, rows = self.treeview.get_selection().get_selected_rows()
return rows
class SequenceListView(ImageTextTextListView):
"""
GUI component displaying list of sequences in project
"""
def __init__(self, seq_name_edited_cb):
ImageTextTextListView.__init__(self)
# Icon path
self.icon_path = respaths.IMAGE_PATH + "sequence.png"
# Set sequence name editable and connect 'edited' signal
self.text_rend_1.set_property("editable", True)
self.text_rend_1.connect("edited",
seq_name_edited_cb,
(self.storemodel, 1))
def fill_data_model(self):
"""
Creates displayed data.
Displays icon, sequence name and sequence length
"""
self.storemodel.clear()
for seq in PROJECT().sequences:
icon = gtk.gdk.pixbuf_new_from_file(self.icon_path)
active = ""
if seq == current_sequence():
active = "<edit>"
row_data = [icon,
seq.name,
active]
self.storemodel.append(row_data)
self.scroll.queue_draw()
class MediaListView(ImageTextTextListView):
"""
GUI component displaying list of media files.
"""
def __init__(self, row_activated_cb, file_name_edited_cb):
ImageTextTextListView.__init__(self)
# Connect double-click listener and allow multiple selection
self.treeview.connect("row-activated",
row_activated_cb)
tree_sel = self.treeview.get_selection()
tree_sel.set_mode(gtk.SELECTION_MULTIPLE)
self.text_rend_1.set_property("editable", True)
self.text_rend_1.set_property("font-desc", pango.FontDescription("sans bold 9"))
self.text_rend_1.connect("edited",
file_name_edited_cb,
(self.storemodel, 1))
self.text_rend_2.set_property("font-desc", pango.FontDescription("sans 8"))
self.text_rend_2.set_property("yalign", 0.5)
def fill_data_model(self):
"""
Creates displayed data.
Displays thumbnail icon, file name and length
"""
self.storemodel.clear()
for file_id in current_bin().file_ids:
media_file = PROJECT().media_files[file_id]
row_data = [media_file.icon,
media_file.name,
utils.clip_length_string(media_file.length)]
self.storemodel.append(row_data)
self.scroll.queue_draw()
class BinListView(ImageTextTextListView):
"""
GUI component displaying list of media files.
"""
def __init__(self, bin_selection_cb, bin_name_edit_cb):
ImageTextTextListView.__init__(self)
self.text_col_1.set_min_width(10)
# Connect selection 'changed' signal
tree_sel = self.treeview.get_selection()
tree_sel.connect("changed", bin_selection_cb)
# Set bin name editable and connect 'edited' signal
self.text_rend_1.set_property("editable", True)
self.text_rend_1.connect("edited",
bin_name_edit_cb,
(self.storemodel, 1))
def fill_data_model(self):
self.storemodel.clear()
for bin in PROJECT().bins:
try:
pixbuf = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "bin_5.png")
row_data = [pixbuf,
bin.name,
str(len(bin.file_ids))]
self.storemodel.append(row_data)
self.scroll.queue_draw()
except gobject.GError, exc:
print "can't load icon", exc
class FilterListView(ImageTextImageListView):
"""
GUI component displaying list of available filters.
"""
def __init__(self, selection_cb=None):
ImageTextImageListView.__init__(self)
# Connect selection 'changed' signal
if not(selection_cb == None):
tree_sel = self.treeview.get_selection()
tree_sel.connect("changed", selection_cb)
def fill_data_model(self, filter_group):
self.storemodel.clear()
for i in range(0, len(filter_group)):
f = filter_group[i]
row_data = [f.get_icon(),
translations.get_filter_name(f.name),
None] # None is historical on/off icon thingy, not used anymore
self.storemodel.append(row_data)
self.scroll.queue_draw()
class FilterSwitchListView(gtk.VBox):
"""
GUI component displaying list of filters applied to a clip.
"""
def __init__(self, selection_cb, toggle_cb):
gtk.VBox.__init__(self)
# Datamodel: icon, text, icon
self.storemodel = gtk.ListStore(gtk.gdk.Pixbuf, str, bool)
# Scroll container
self.scroll = gtk.ScrolledWindow()
self.scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
self.scroll.set_shadow_type(gtk.SHADOW_ETCHED_IN)
# View
self.treeview = gtk.TreeView(self.storemodel)
self.treeview.set_property("rules_hint", True)
self.treeview.set_headers_visible(False)
tree_sel = self.treeview.get_selection()
tree_sel.set_mode(gtk.SELECTION_SINGLE)
# Column views
self.icon_col_1 = gtk.TreeViewColumn("icon1")
self.text_col_1 = gtk.TreeViewColumn("text1")
self.check_col_1 = gtk.TreeViewColumn("switch")
# Cell renderers
self.icon_rend_1 = gtk.CellRendererPixbuf()
self.icon_rend_1.props.xpad = 6
self.text_rend_1 = gtk.CellRendererText()
self.text_rend_1.set_property("ellipsize", pango.ELLIPSIZE_END)
self.toggle_rend = gtk.CellRendererToggle()
self.toggle_rend.set_property('activatable', True)
self.toggle_rend.connect( 'toggled', self.toggled)
# Build column views
self.icon_col_1.set_expand(False)
self.icon_col_1.set_spacing(5)
self.icon_col_1.pack_start(self.icon_rend_1)
self.icon_col_1.add_attribute(self.icon_rend_1, 'pixbuf', 0)
self.text_col_1.set_expand(True)
self.text_col_1.set_spacing(5)
self.text_col_1.set_sizing(gtk.TREE_VIEW_COLUMN_GROW_ONLY)
self.text_col_1.set_min_width(150)
self.text_col_1.pack_start(self.text_rend_1)
self.text_col_1.add_attribute(self.text_rend_1, "text", 1)
self.check_col_1.set_expand(False)
self.check_col_1.set_spacing(5)
self.check_col_1.pack_start(self.toggle_rend)
self.check_col_1.add_attribute(self.toggle_rend, "active", 2)
# Add column views to view
self.treeview.append_column(self.icon_col_1)
self.treeview.append_column(self.text_col_1)
self.treeview.append_column(self.check_col_1)
# Build widget graph and display
self.scroll.add(self.treeview)
self.pack_start(self.scroll)
self.scroll.show_all()
# Connect selection 'changed' signal
if not(selection_cb == None):
tree_sel = self.treeview.get_selection()
tree_sel.connect("changed", selection_cb)
self.toggle_callback = toggle_cb
def get_selected_rows_list(self):
model, rows = self.treeview.get_selection().get_selected_rows()
return rows
def fill_data_model(self, filter_group, filter_objects):
"""
Creates displayed data.
Displays thumbnail icon, file name and length
filter_group is array of mltfilter.FilterInfo objects.
filter_obejcts is array of mltfilter.FilterObject objects
"""
self.storemodel.clear()
for i in range(0, len(filter_group)):
f = filter_group[i]
row_data = [f.get_icon(),
translations.get_filter_name(f.name),
filter_objects[i].active]
self.storemodel.append(row_data)
self.scroll.queue_draw()
def toggled(self, cell, path):
self.toggle_callback(int(path))
class TextListView(gtk.VBox):
"""
GUI component displaying list with single column text column.
"""
def __init__(self, width, column_name=None):
gtk.VBox.__init__(self)
# Datamodel: icon, text, text
self.storemodel = gtk.ListStore(str)
# Scroll container
self.scroll = gtk.ScrolledWindow()
self.scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
self.scroll.set_shadow_type(gtk.SHADOW_ETCHED_IN)
# View
self.treeview = gtk.TreeView(self.storemodel)
self.treeview.set_property("rules_hint", True)
if column_name == None:
self.treeview.set_headers_visible(False)
column_name = "text1"
self.treeview.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
# Cell renderers
self.text_rend_1 = gtk.CellRendererText()
self.text_rend_1.set_property("ellipsize", pango.ELLIPSIZE_END)
# Build column views
self.text_col_1 = gtk.TreeViewColumn(column_name)
self.text_col_1.set_expand(True)
self.text_col_1.set_spacing(5)
self.text_col_1.set_sizing(gtk.TREE_VIEW_COLUMN_GROW_ONLY)
self.text_col_1.set_min_width(width)
self.text_col_1.pack_start(self.text_rend_1)
self.text_col_1.add_attribute(self.text_rend_1, "text", 0)
# Add column views to view
self.treeview.append_column(self.text_col_1)
# Build widget graph and display
self.scroll.add(self.treeview)
self.pack_start(self.scroll)
self.scroll.show_all()
def get_selected_rows_list(self):
model, rows = self.treeview.get_selection().get_selected_rows()
return rows
def get_selected_indexes_list(self):
rows = self.get_selected_rows_list()
indexes = []
for row in rows:
indexes.append(max(row))
return indexes
class ProfileListView(TextListView):
"""
GUI component displaying list with columns: img, text, text
Middle column expands.
"""
def __init__(self, column_name=None):
TextListView.__init__(self, 100, column_name)
def fill_data_model(self, profiles):
self.storemodel.clear()
default_profile = mltprofiles.get_default_profile()
for profile in profiles:
row_data = [profile[0]]
if default_profile == profile[1]:
row_data = [row_data[0] + " <" + _("default") + ">"]
self.storemodel.append(row_data)
self.scroll.queue_draw()
class AutoSavesListView(TextListView):
def __init__(self, column_name=None):
TextListView.__init__(self, 300, None)
self.treeview.get_selection().set_mode(gtk.SELECTION_SINGLE)
def fill_data_model(self, autosaves):
self.storemodel.clear()
for autosave_object in autosaves:
since_time_str = utils.get_time_str_for_sec_float(autosave_object.age)
row_data = ["Autosave created " + since_time_str + " ago."]
self.storemodel.append(row_data)
self.treeview.set_cursor("0")
self.scroll.queue_draw()
# -------------------------------------------- clip info
class ClipInfoPanel(gtk.VBox):
def __init__(self):
gtk.VBox.__init__(self, False, 2)
self.name_label = guiutils.bold_label(_("Clip:"))
self.name_value = gtk.Label()
self.name_value.set_ellipsize(pango.ELLIPSIZE_END)
self.track = guiutils.bold_label(_("Track:"))
self.track_value = gtk.Label()
self.position = guiutils.bold_label(_("Pos:"))
self.position_value = gtk.Label()
info_row_1 = gtk.HBox()
info_row_1.pack_start(self.name_label, False, True, 0)
info_row_1.pack_start(self.name_value, True, True, 0)
info_row_2 = gtk.HBox()
info_row_2.pack_start(self.track, False, False, 0)
info_row_2.pack_start(self.track_value, True, True, 0)
info_row_3 = gtk.HBox()
info_row_3.pack_start(self.position, False, False, 0)
info_row_3.pack_start(self.position_value, True, True, 0)
self.pack_start(info_row_1, False, False, 0)
self.pack_start(info_row_2, False, False, 0)
self.pack_start(info_row_3, False, False, 0)
self.set_size_request(CLIP_EDITOR_LEFT_WIDTH, 56)
def display_clip_info(self, clip, track, index):
self.name_label.set_text(_("<b>Clip: </b>"))
self.name_value.set_text(clip.name)
self.track.set_text(_("<b>Track: </b>"))
self.track_value.set_text(track.get_name())
self.position.set_text(_("<b>Position:</b>"))
clip_start_in_tline = track.clip_start(index)
tc_str = utils.get_tc_string(clip_start_in_tline)
self.position_value.set_text(tc_str)
self._set_use_mark_up()
def set_no_clip_info(self):
self.name_label.set_text(_("<b>Clip:</b>"))
self.name_value.set_text("")
self.track.set_text(_("<b>Track:</b>"))
self.track_value.set_text("")
self.position.set_text(_("<b>Position:</b>"))
self.position_value.set_text("")
self._set_use_mark_up()
def _set_use_mark_up(self):
self.name_label.set_use_markup(True)
self.track.set_use_markup(True)
self.position.set_use_markup(True)
def set_enabled(self, value):
self.name_label.set_sensitive(value)
self.track.set_sensitive(value)
self.position.set_sensitive(value)
class CompositorInfoPanel(gtk.VBox):
def __init__(self):
gtk.VBox.__init__(self, False, 2)
self.source_track = gtk.Label()
self.source_track_value = gtk.Label()
self.destination_track = gtk.Label()
self.destination_track_value = gtk.Label()
self.position = gtk.Label()
self.position_value = gtk.Label()
self.length = gtk.Label()
self.length_value = gtk.Label()
info_row_2 = gtk.HBox()
info_row_2.pack_start(self.source_track, False, True, 0)
info_row_2.pack_start(self.source_track_value, True, True, 0)
info_row_3 = gtk.HBox()
info_row_3.pack_start(self.destination_track, False, True, 0)
info_row_3.pack_start(self.destination_track_value, True, True, 0)
info_row_4 = gtk.HBox()
info_row_4.pack_start(self.position, False, True, 0)
info_row_4.pack_start(self.position_value, True, True, 0)
info_row_5 = gtk.HBox()
info_row_5.pack_start(self.length, False, False, 0)
info_row_5.pack_start(self.length_value, True, True, 0)
PAD_HEIGHT = 2
self.pack_start(info_row_2, False, False, 0)
self.pack_start(guiutils.get_pad_label(5, PAD_HEIGHT), False, False, 0)
self.pack_start(info_row_3, False, False, 0)
self.pack_start(guiutils.get_pad_label(5, PAD_HEIGHT), False, False, 0)
self.pack_start(info_row_4, False, False, 0)
self.pack_start(guiutils.get_pad_label(5, PAD_HEIGHT), False, False, 0)
self.pack_start(info_row_5, False, False, 0)
self.set_no_compositor_info()
self.set_enabled(False)
def display_compositor_info(self, compositor):
src_track = utils.get_track_name(current_sequence().tracks[compositor.transition.b_track],current_sequence())
self.source_track_value.set_text(src_track)
dest_track = utils.get_track_name(current_sequence().tracks[compositor.transition.a_track], current_sequence())
self.destination_track_value.set_text(dest_track)
pos = utils.get_tc_string(compositor.clip_in)
self.position_value.set_text(pos)
length = utils.get_tc_string(compositor.clip_out - compositor.clip_in)
self.length_value.set_text(length)
def set_no_compositor_info(self):
self.source_track.set_text(_("<b>Source Track:</b>"))
self.source_track_value.set_text("")
self.destination_track.set_text(_("<b>Destination Track:</b>"))
self.destination_track_value.set_text("")
self.position.set_text(_("<b>Position:</b>"))
self.position_value.set_text("")
self.length.set_text(_("<b>Length:</b>"))
self.length_value.set_text("")
self._set_use_mark_up()
def _set_use_mark_up(self):
self.source_track.set_use_markup(True)
self.destination_track.set_use_markup(True)
self.position.set_use_markup(True)
self.length.set_use_markup(True)
def set_enabled(self, value):
self.source_track.set_sensitive(value)
self.destination_track.set_sensitive(value)
self.position.set_sensitive(value)
self.length.set_sensitive(value)
# -------------------------------------------- media select panel
class MediaPanel():
def __init__(self, media_file_popup_cb, double_click_cb):
self.widget = gtk.VBox()
self.row_widgets = []
self.selected_objects = []
self.columns = editorpersistance.prefs.media_columns
self.media_file_popup_cb = media_file_popup_cb
self.double_click_cb = double_click_cb
self.monitor_indicator = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "monitor_indicator.png")
global has_proxy_icon, is_proxy_icon, graphics_icon, imgseq_icon, audio_icon, pattern_icon
has_proxy_icon = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "has_proxy_indicator.png")
is_proxy_icon = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "is_proxy_indicator.png")
graphics_icon = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "graphics_indicator.png")
imgseq_icon = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "imgseq_indicator.png")
audio_icon = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "audio_indicator.png")
pattern_icon = gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "pattern_producer_indicator.png")
def get_selected_media_objects(self):
return self.selected_objects
def media_object_selected(self, media_object, widget, event):
widget.grab_focus()
if event.type == gtk.gdk._2BUTTON_PRESS:
self.double_click_cb(media_object.media_file)
elif event.button == 1:
if (event.state & gtk.gdk.CONTROL_MASK):
widget.modify_bg(gtk.STATE_NORMAL, gui.selected_bg_color)
# only add to selected if not already there
try:
self.selected_objects.index(media_object)
except:
self.selected_objects.append(media_object)
else:
self.clear_selection()
widget.modify_bg(gtk.STATE_NORMAL, gui.selected_bg_color)
self.selected_objects.append(media_object)
elif event.button == 3:
self.clear_selection()
display_media_file_popup_menu(media_object.media_file,
self.media_file_popup_cb,
event)
elif event.type == gtk.gdk._2BUTTON_PRESS:
print "double click"
self.widget.queue_draw()
def select_media_file(self, media_file):
self.clear_selection()
self.selected_objects.append(self.widget_for_mediafile[media_file])
def select_media_file_list(self, media_files):
self.clear_selection()
for media_file in media_files:
self.selected_objects.append(self.widget_for_mediafile[media_file])
def empty_pressed(self, widget, event):
self.clear_selection()
def select_all(self):
self.clear_selection()
for media_file, media_object in self.widget_for_mediafile.iteritems():
media_object.widget.modify_bg(gtk.STATE_NORMAL, gui.selected_bg_color)
self.selected_objects.append(media_object)
def clear_selection(self):
for m_obj in self.selected_objects:
m_obj.widget.modify_bg(gtk.STATE_NORMAL, gui.note_bg_color)
self.selected_objects = []
def columns_changed(self, adjustment):
self.columns = int(adjustment.get_value())
editorpersistance.prefs.media_columns = self.columns
editorpersistance.save()
self.fill_data_model()
def fill_data_model(self):
for w in self.row_widgets:
self.widget.remove(w)
self.row_widgets = []
self.widget_for_mediafile = {}
self.selected_objects = []
column = 0
bin_index = 0
row_box = gtk.HBox()
row_box.set_size_request(MEDIA_OBJECT_WIDGET_WIDTH * self.columns, MEDIA_OBJECT_WIDGET_HEIGHT)
for file_id in current_bin().file_ids:
media_file = PROJECT().media_files[file_id]
# Filter view
if ((editorstate.media_view_filter == appconsts.SHOW_VIDEO_FILES)
and (media_file.type != appconsts.VIDEO)):
continue
if ((editorstate.media_view_filter == appconsts.SHOW_AUDIO_FILES)
and (media_file.type != appconsts.AUDIO)):
continue
if ((editorstate.media_view_filter == appconsts.SHOW_GRAPHICS_FILES)
and (media_file.type != appconsts.IMAGE)):
continue
if ((editorstate.media_view_filter == appconsts.SHOW_IMAGE_SEQUENCES)
and (media_file.type != appconsts.IMAGE_SEQUENCE)):
continue
if ((editorstate.media_view_filter == appconsts.SHOW_PATTERN_PRODUCERS)
and (media_file.type != appconsts.PATTERN_PRODUCER)):
continue
media_object = MediaObjectWidget(media_file, self.media_object_selected, bin_index, self.monitor_indicator)
dnd.connect_media_files_object_widget(media_object.widget)
dnd.connect_media_files_object_cairo_widget(media_object.img)
self.widget_for_mediafile[media_file] = media_object
row_box.pack_start(media_object.widget, False, False, 0)
column += 1
if column == self.columns:
filler = self._get_empty_filler()
row_box.pack_start(filler, True, True, 0)
self.widget.pack_start(row_box, False, False, 0)
self.row_widgets.append(row_box)
row_box = gtk.HBox()
column = 0
bin_index += 1
if column != 0:
filler = self._get_empty_filler()
row_box.pack_start(filler, True, True, 0)
self.widget.pack_start(row_box, False, False, 0)
self.row_widgets.append(row_box)
filler = self._get_empty_filler()
self.row_widgets.append(filler)
self.widget.pack_start(filler, True, True, 0)
self.widget.show_all()
def _get_empty_filler(self):
filler = gtk.EventBox()
filler.connect("button-press-event", lambda w,e: self.empty_pressed(w,e))
filler.add(gtk.Label())
return filler
class MediaObjectWidget:
def __init__(self, media_file, selected_callback, bin_index, indicator_icon):
self.media_file = media_file
self.selected_callback = selected_callback
self.bin_index = bin_index
self.indicator_icon = indicator_icon
self.selected_callback = selected_callback
self.widget = gtk.EventBox()
self.widget.connect("button-press-event", lambda w,e: selected_callback(self, w, e))
self.widget.dnd_media_widget_attr = True # this is used to identify widget at dnd drop
self.widget.set_can_focus(True)
self.align = gtk.Alignment()
self.align.set_padding(3, 2, 3, 2)
self.align.set_size_request(MEDIA_OBJECT_WIDGET_WIDTH, MEDIA_OBJECT_WIDGET_HEIGHT)
self.vbox = gtk.VBox()
self.img = CairoDrawableArea(appconsts.THUMB_WIDTH, appconsts.THUMB_HEIGHT, self._draw_icon)
self.img.press_func = self._press
self.img.dnd_media_widget_attr = True # this is used to identify widget at dnd drop
txt = gtk.Label(media_file.name)
txt.modify_font(pango.FontDescription("sans 9"))
txt.set_ellipsize(pango.ELLIPSIZE_END)
self.vbox.pack_start(self.img, True, True, 0)
self.vbox.pack_start(txt, False, False, 0)
self.align.add(self.vbox)
self.widget.add(self.align)
def _press(self, event):
self.selected_callback(self, self.widget, event)
def _draw_icon(self, event, cr, allocation):
x, y, w, h = allocation
cr.set_source_pixbuf(self.media_file.icon, 0, 0)
cr.paint()
if self.media_file == editorstate.MONITOR_MEDIA_FILE():
cr.set_source_pixbuf(self.indicator_icon, 29, 22)
cr.paint()
if self.media_file.mark_in != -1 and self.media_file.mark_out != -1:
cr.set_source_rgb(1, 1, 1)
cr.select_font_face ("sans-serif",
cairo.FONT_SLANT_NORMAL,
cairo.FONT_WEIGHT_NORMAL)
cr.set_font_size(9)
cr.move_to(23, 80)
clip_length = utils.get_tc_string(self.media_file.mark_out - self.media_file.mark_in + 1) #+1 out incl.
cr.show_text("][ " + str(clip_length))
if self.media_file.type != appconsts.PATTERN_PRODUCER:
if self.media_file.is_proxy_file == True:
cr.set_source_pixbuf(is_proxy_icon, 96, 6)
cr.paint()
elif self.media_file.has_proxy_file == True:
cr.set_source_pixbuf(has_proxy_icon, 96, 6)
cr.paint()
if self.media_file.type == appconsts.IMAGE:
cr.set_source_pixbuf(graphics_icon, 6, 6)
cr.paint()
if self.media_file.type == appconsts.IMAGE_SEQUENCE:
cr.set_source_pixbuf(imgseq_icon, 6, 6)
cr.paint()
if self.media_file.type == appconsts.AUDIO:
cr.set_source_pixbuf(audio_icon, 6, 6)
cr.paint()
if self.media_file.type == appconsts.PATTERN_PRODUCER:
cr.set_source_pixbuf(pattern_icon, 6, 6)
cr.paint()
# -------------------------------------------- context menus
class EditorSeparator:
"""
GUI component used to add, move and remove keyframes to of
inside a single clip. Does not a reference of the property being
edited and needs a parent editor to write keyframe values.
"""
def __init__(self):
self.widget = CairoDrawableArea(SEPARATOR_WIDTH,
SEPARATOR_HEIGHT,
self._draw)
def _draw(self, event, cr, allocation):
"""
Callback for repaint from CairoDrawableArea.
We get cairo contect and allocation.
"""
x, y, w, h = allocation
# Draw bg
cr.set_source_rgb(*(gui.bg_color_tuple))
cr.rectangle(0, 0, w, h)
cr.fill()
# Draw separator
cr.set_line_width(1.0)
r,g,b = gui.fg_color_tuple
cr.set_source_rgba(r,g,b,0.2)
cr.move_to(8.5, 2.5)
cr.line_to(w - 8.5, 2.5)
cr.stroke()
# ---------------------------------------------- MISC WIDGETS
def get_monitor_view_select_combo(callback):
pixbuf_list = [gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "program_view_2.png"),
gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "vectorscope.png"),
gtk.gdk.pixbuf_new_from_file(respaths.IMAGE_PATH + "rgbparade.png")]
menu_launch = ImageMenuLaunch(callback, pixbuf_list, w=24, h=20)
menu_launch.pixbuf_y = 10
return menu_launch
def get_compositor_track_select_combo(source_track, target_track, callback):
tracks_combo = gtk.combo_box_new_text()
#tracks_combo.append_text("Auto Track Below")
active_index = -1
cb_index = 0
for track_index in range(source_track.id - 1, current_sequence().first_video_index - 1, -1):
track = current_sequence().tracks[track_index]
tracks_combo.append_text(utils.get_track_name(track, current_sequence()))
if track == target_track:
active_index = cb_index
cb_index += 1
if active_index == -1:
tracks_combo.set_active(0)
else:
tracks_combo.set_active(active_index)
tracks_combo.connect("changed", lambda w,e: callback(w), None)
return tracks_combo
# -------------------------------------------- context menus
def display_tracks_popup_menu(event, track, callback):
track_obj = current_sequence().tracks[track]
track_menu = gtk.Menu()
if track_obj.edit_freedom != appconsts.FREE:
track_menu.append(_get_menu_item(_("Lock Track"), callback, (track,"lock", None), False))
track_menu.append(_get_menu_item(_("Unlock Track"), callback, (track,"unlock", None), True))
else:
track_menu.append(_get_menu_item(_("Lock Track"), callback, (track,"lock", None), True))
track_menu.append(_get_menu_item(_("Unlock Track"), callback, (track,"unlock", None), False))
_add_separetor(track_menu)
normal_size_item = _get_radio_menu_item(_("Large Height"), callback, None)
normal_size_item.set_active(track_obj.height == appconsts.TRACK_HEIGHT_NORMAL)
normal_size_item.connect("activate", callback, (track, "normal_height", None))
track_menu.append(normal_size_item)
small_size_item = _get_radio_menu_item(_("Normal Height"), callback, normal_size_item)
small_size_item.set_active(track_obj.height != appconsts.TRACK_HEIGHT_NORMAL)
small_size_item.connect("activate", callback, (track, "small_height", None))
track_menu.append(small_size_item)
_add_separetor(track_menu)
track_menu.append(_get_track_mute_menu_item(event, track_obj, callback))
track_menu.popup(None, None, None, event.button, event.time)
def display_clip_popup_menu(event, clip, track, callback):
if clip.is_blanck_clip:
display_blank_clip_popup_menu(event, clip, track, callback)
return
if hasattr(clip, "rendered_type"):
display_transition_clip_popup_menu(event, clip, track, callback)
return
clip_menu = gtk.Menu()
clip_menu.add(_get_menu_item(_("Open in Filters Editor"), callback, (clip, track, "open_in_editor", event.x)))
# Only make opening in compositor editor for video tracks V2 and higher
if track.id <= current_sequence().first_video_index:
active = False
else:
active = True
if clip.media_type != appconsts.PATTERN_PRODUCER:
clip_menu.add(_get_menu_item(_("Open in Clip Monitor"), callback,\
(clip, track, "open_in_clip_monitor", event.x)))
_add_separetor(clip_menu)
if track.type == appconsts.VIDEO:
clip_menu.add(_get_menu_item(_("Split Audio"), callback,\
(clip, track, "split_audio", event.x), True))
if track.id == current_sequence().first_video_index:
active = True
else:
active = False
clip_menu.add(_get_menu_item(_("Split Audio Synched"), callback,\
(clip, track, "split_audio_synched", event.x), active))
_add_separetor(clip_menu)
if clip.waveform_data == None:
clip_menu.add(_get_menu_item(_("Display Audio Level"), callback,\
(clip, track, "display_waveform", event.x), True))
else:
clip_menu.add(_get_menu_item(_("Clear Waveform"), callback,\
(clip, track, "clear_waveform", event.x), True))
_add_separetor(clip_menu)
if track.id != current_sequence().first_video_index:
if clip.sync_data != None:
clip_menu.add(_get_menu_item(_("Resync"), callback, (clip, track, "resync", event.x)))
clip_menu.add(_get_menu_item(_("Clear Sync Relation"), callback, (clip, track, "clear_sync_rel", event.x)))
else:
clip_menu.add(_get_menu_item(_("Select Sync Parent Clip..."), callback, (clip, track, "set_master", event.x)))
_add_separetor(clip_menu)
clip_menu.add(_get_mute_menu_item(event, clip, track, callback))
_add_separetor(clip_menu)
clip_menu.add(_get_filters_add_menu_item(event, clip, track, callback))
# Only add compositors for video tracks V2 and higher
if track.id <= current_sequence().first_video_index:
active = False
else:
active = True
clip_menu.add(_get_compositors_add_menu_item(event, clip, track, callback, active))
clip_menu.add(_get_blenders_add_menu_item(event, clip, track, callback, active))
_add_separetor(clip_menu)
clip_menu.add(_get_clone_filters_menu_item(event, clip, track, callback))
_add_separetor(clip_menu)
clip_menu.add(_get_menu_item(_("Rename Clip"), callback,\
(clip, track, "rename_clip", event.x)))
clip_menu.add(_get_color_menu_item(clip, track, callback))
clip_menu.add(_get_menu_item(_("Clip Info"), callback,\
(clip, track, "clip_info", event.x)))
clip_menu.popup(None, None, None, event.button, event.time)
def display_transition_clip_popup_menu(event, clip, track, callback):
clip_menu = gtk.Menu()
clip_menu.add(_get_menu_item(_("Open in Filters Editor"), callback, (clip, track, "open_in_editor", event.x)))
_add_separetor(clip_menu)
clip_menu.add(_get_mute_menu_item(event, clip, track, callback))
_add_separetor(clip_menu)
clip_menu.add(_get_filters_add_menu_item(event, clip, track, callback))
# Only add compositors for video tracks V2 and higher
if track.id <= current_sequence().first_video_index:
active = False
else:
active = True
clip_menu.add(_get_compositors_add_menu_item(event, clip, track, callback, active))
clip_menu.add(_get_blenders_add_menu_item(event, clip, track, callback, active))
_add_separetor(clip_menu)
clip_menu.add(_get_clone_filters_menu_item(event, clip, track, callback))
clip_menu.popup(None, None, None, event.button, event.time)
def display_blank_clip_popup_menu(event, clip, track, callback):
clip_menu = gtk.Menu()
clip_menu.add(_get_menu_item(_("Strech Prev Clip to Cover"), callback, (clip, track, "cover_with_prev", event.x)))
clip_menu.add(_get_menu_item(_("Strech Next Clip to Cover"), callback, (clip, track, "cover_with_next", event.x)))
_add_separetor(clip_menu)
clip_menu.add(_get_menu_item(_("Delete"), callback, (clip, track, "delete_blank", event.x)))
clip_menu.popup(None, None, None, event.button, event.time)
def display_audio_clip_popup_menu(event, clip, track, callback):
if clip.is_blanck_clip:
display_blank_clip_popup_menu(event, clip, track, callback)
return
clip_menu = gtk.Menu()
clip_menu.add(_get_menu_item(_("Open in Filters Editor"), callback, (clip, track, "open_in_editor", event.x)))
if clip.media_type != appconsts.PATTERN_PRODUCER:
clip_menu.add(_get_menu_item(_("Open in Clip Monitor"), callback,\
(clip, track, "open_in_clip_monitor", event.x)))
_add_separetor(clip_menu)
if clip.sync_data != None:
clip_menu.add(_get_menu_item(_("Resync"), callback, (clip, track, "resync", event.x)))
clip_menu.add(_get_menu_item(_("Clear Sync Relation"), callback, (clip, track, "clear_sync_rel", event.x)))
else:
clip_menu.add(_get_menu_item(_("Select Sync Parent Clip..."), callback, (clip, track, "set_master", event.x)))
_add_separetor(clip_menu)
if clip.waveform_data == None:
clip_menu.add(_get_menu_item(_("Display Audio Level"), callback,\
(clip, track, "display_waveform", event.x), True))
else:
clip_menu.add(_get_menu_item(_("Clear Waveform"), callback,\
(clip, track, "clear_waveform", event.x), True))
_add_separetor(clip_menu)
clip_menu.add(_get_mute_menu_item(event, clip, track, callback))
_add_separetor(clip_menu)
clip_menu.add(_get_audio_filters_add_menu_item(event, clip, track, callback))
_add_separetor(clip_menu)
clip_menu.add(_get_menu_item(_("Rename Clip"), callback,\
(clip, track, "rename_clip", event.x)))
clip_menu.add(_get_color_menu_item(clip, track, callback))
clip_menu.add(_get_menu_item(_("Clip Info"), callback,\
(clip, track, "clip_info", event.x)))
clip_menu.popup(None, None, None, event.button, event.time)
def display_compositor_popup_menu(event, compositor, callback):
compositor_menu = gtk.Menu()
compositor_menu.add(_get_menu_item(_("Open In Compositor Editor"), callback, ("open in editor",compositor)))
_add_separetor(compositor_menu)
compositor_menu.add(_get_menu_item(_("Sync with Origin Clip"), callback, ("sync with origin",compositor)))
_add_separetor(compositor_menu)
compositor_menu.add(_get_menu_item(_("Delete"), callback, ("delete",compositor)))
compositor_menu.popup(None, None, None, event.button, event.time)
def _get_filters_add_menu_item(event, clip, track, callback):
menu_item = gtk.MenuItem(_("Add Filter"))
sub_menu = gtk.Menu()
menu_item.set_submenu(sub_menu)
for group in mltfilters.groups:
group_name, filters_array = group
group_item = gtk.MenuItem(group_name)
sub_menu.append(group_item)
sub_sub_menu = gtk.Menu()
group_item.set_submenu(sub_sub_menu)
for filter_info in filters_array:
filter_item = gtk.MenuItem(translations.get_filter_name(filter_info.name))
sub_sub_menu.append(filter_item)
filter_item.connect("activate", callback, (clip, track, "add_filter", (event.x, filter_info)))
filter_item.show()
group_item.show()
menu_item.show()
return menu_item
def _get_audio_filters_add_menu_item(event, clip, track, callback):
menu_item = gtk.MenuItem(_("Add Filter"))
sub_menu = gtk.Menu()
menu_item.set_submenu(sub_menu)
audio_groups = mltfilters.get_audio_filters_groups()
for group in audio_groups:
group_name, filters_array = group
group_item = gtk.MenuItem(group_name)
sub_menu.append(group_item)
sub_sub_menu = gtk.Menu()
group_item.set_submenu(sub_sub_menu)
for filter_info in filters_array:
filter_item = gtk.MenuItem(translations.get_filter_name(filter_info.name))
sub_sub_menu.append(filter_item)
filter_item.connect("activate", callback, (clip, track, "add_filter", (event.x, filter_info)))
filter_item.show()
group_item.show()
menu_item.show()
return menu_item
def _get_compositors_add_menu_item(event, clip, track, callback, sensitive):
menu_item = gtk.MenuItem(_("Add Compositor"))
sub_menu = gtk.Menu()
menu_item.set_submenu(sub_menu)
for i in range(0, len(mlttransitions.compositors)):
compositor = mlttransitions.compositors[i]
name, compositor_type = compositor
# Continue if compositor_type not present in system
try:
info = mlttransitions.mlt_compositor_transition_infos[compositor_type]
except:
continue
compositor_item = gtk.MenuItem(name)
sub_menu.append(compositor_item)
compositor_item.connect("activate", callback, (clip, track, "add_compositor", (event.x, compositor_type)))
compositor_item.show()
menu_item.set_sensitive(sensitive)
menu_item.show()
return menu_item
def _get_blenders_add_menu_item(event, clip, track, callback, sensitive):
menu_item = gtk.MenuItem(_("Add Blend"))
sub_menu = gtk.Menu()
menu_item.set_submenu(sub_menu)
for i in range(0, len(mlttransitions.blenders)):
blend = mlttransitions.blenders[i]
name, compositor_type = blend
blender_item = gtk.MenuItem(name)
sub_menu.append(blender_item)
blender_item.connect("activate", callback, (clip, track, "add_compositor", (event.x, compositor_type)))
blender_item.show()
menu_item.set_sensitive(sensitive)
menu_item.show()
return menu_item
def _get_clone_filters_menu_item(event, clip, track, callback):
menu_item = gtk.MenuItem(_("Clone Filters"))
sub_menu = gtk.Menu()
menu_item.set_submenu(sub_menu)
clone_item = gtk.MenuItem(_("From Next Clip"))
sub_menu.append(clone_item)
clone_item.connect("activate", callback, (clip, track, "clone_filters_from_next", None))
clone_item.show()
clone_item = gtk.MenuItem(_("From Previous Clip"))
sub_menu.append(clone_item)
clone_item.connect("activate", callback, (clip, track, "clone_filters_from_prev", None))
clone_item.show()
menu_item.show()
return menu_item
def _get_mute_menu_item(event, clip, track, callback):
menu_item = gtk.MenuItem(_("Mute"))
sub_menu = gtk.Menu()
menu_item.set_submenu(sub_menu)
item = gtk.MenuItem(_("Unmute"))
sub_menu.append(item)
item.connect("activate", callback, (clip, track, "mute_clip", (False)))
item.show()
item.set_sensitive(not(clip.mute_filter==None))
item = gtk.MenuItem(_("Mute Audio"))
sub_menu.append(item)
item.connect("activate", callback, (clip, track, "mute_clip", (True)))
item.show()
item.set_sensitive(clip.mute_filter==None)
menu_item.show()
return menu_item
def _get_track_mute_menu_item(event, track, callback):
menu_item = gtk.MenuItem(_("Mute"))
sub_menu = gtk.Menu()
menu_item.set_submenu(sub_menu)
item = gtk.MenuItem(_("Unmute"))
sub_menu.append(item)
if track.type == appconsts.VIDEO:
item.connect("activate", callback, (track, "mute_track", appconsts.TRACK_MUTE_NOTHING))
_set_non_sensitive_if_state_matches(track, item, appconsts.TRACK_MUTE_NOTHING)
else:
item.connect("activate", callback, (track, "mute_track", appconsts.TRACK_MUTE_VIDEO))
_set_non_sensitive_if_state_matches(track, item, appconsts.TRACK_MUTE_VIDEO)
item.show()
if track.type == appconsts.VIDEO:
item = gtk.MenuItem(_("Mute Video"))
sub_menu.append(item)
item.connect("activate", callback, (track, "mute_track", appconsts.TRACK_MUTE_VIDEO))
_set_non_sensitive_if_state_matches(track, item, appconsts.TRACK_MUTE_VIDEO)
item.show()
item = gtk.MenuItem(_("Mute Audio"))
sub_menu.append(item)
if track.type == appconsts.VIDEO:
item.connect("activate", callback, (track, "mute_track", appconsts.TRACK_MUTE_AUDIO))
_set_non_sensitive_if_state_matches(track, item, appconsts.TRACK_MUTE_AUDIO)
else:
item.connect("activate", callback, (track, "mute_track", appconsts.TRACK_MUTE_ALL))
_set_non_sensitive_if_state_matches(track, item, appconsts.TRACK_MUTE_ALL)
item.show()
if track.type == appconsts.VIDEO:
item = gtk.MenuItem(_("Mute All"))
sub_menu.append(item)
item.connect("activate", callback, (track, "mute_track", appconsts.TRACK_MUTE_ALL))
_set_non_sensitive_if_state_matches(track, item, appconsts.TRACK_MUTE_ALL)
item.show()
menu_item.show()
return menu_item
def _get_color_menu_item(clip, track, callback):
color_menu_item = gtk.MenuItem(_("Clip Color"))
color_menu = gtk.Menu()
color_menu.add(_get_menu_item(_("Default"), callback, (clip, track, "clip_color", "default")))
color_menu.add(_get_menu_item(_("Red"), callback, (clip, track, "clip_color", "red")))
color_menu.add(_get_menu_item(_("Green"), callback, (clip, track, "clip_color", "green")))
color_menu.add(_get_menu_item(_("Blue"), callback, (clip, track, "clip_color", "blue")))
color_menu.add(_get_menu_item(_("Orange"), callback, (clip, track, "clip_color", "orange")))
color_menu.add(_get_menu_item(_("Brown"), callback, (clip, track, "clip_color", "brown")))
color_menu.add(_get_menu_item(_("Olive"), callback, (clip, track, "clip_color", "olive")))
color_menu_item.set_submenu(color_menu)
color_menu_item.show_all()
return color_menu_item
def _set_non_sensitive_if_state_matches(mutable, item, state):
if mutable.mute_state == state:
item.set_sensitive(False)
def display_media_file_popup_menu(media_file, callback, event):
media_file_menu = gtk.Menu()
# "Open in Clip Monitor" is sent as event id, same for all below
media_file_menu.add(_get_menu_item(_("Rename"), callback,("Rename", media_file, event)))
media_file_menu.add(_get_menu_item(_("Delete"), callback,("Delete", media_file, event)))
_add_separetor(media_file_menu)
media_file_menu.add(_get_menu_item(_("Open in Clip Monitor"), callback,("Open in Clip Monitor", media_file, event)))
media_file_menu.add(_get_menu_item(_("File Properties"), callback, ("File Properties", media_file, event)))
_add_separetor(media_file_menu)
media_file_menu.add(_get_menu_item(_("Render Slow/Fast Motion File"), callback, ("Render Slow/Fast Motion File", media_file, event)))
item = _get_menu_item(_("Render Proxy File"), callback, ("Render Proxy File", media_file, event))
media_file_menu.add(item)
media_file_menu.popup(None, None, None, event.button, event.time)
def display_filter_stack_popup_menu(row, treeview, callback, event):
filter_stack_menu = gtk.Menu()
filter_stack_menu.add(_get_menu_item(_("Toggle Active"), callback, ("toggle", row, treeview)))
filter_stack_menu.add(_get_menu_item(_("Reset Values"), callback, ("reset", row, treeview)))
filter_stack_menu.popup(None, None, None, event.button, event.time)
def display_media_log_event_popup_menu(row, treeview, callback, event):
log_event_menu = gtk.Menu()
log_event_menu.add(_get_menu_item(_("Display In Clip Monitor"), callback, ("display", row, treeview)))
log_event_menu.add(_get_menu_item(_("Toggle Star"), callback, ("toggle", row, treeview)))
log_event_menu.add(_get_menu_item(_("Delete"), callback, ("delete", row, treeview)))
log_event_menu.popup(None, None, None, event.button, event.time)
def display_media_linker_popup_menu(row, treeview, callback, event):
media_linker_menu = gtk.Menu()
media_linker_menu.add(_get_menu_item(_("Set File Relink Path"), callback, ("set relink", row)))
media_linker_menu.add(_get_menu_item(_("Delete File Relink Path"), callback, ("delete relink", row)))
_add_separetor(media_linker_menu)
media_linker_menu.add(_get_menu_item(_("Show Full Paths"), callback, ("show path", row)))
media_linker_menu.popup(None, None, None, event.button, event.time)
def _add_separetor(menu):
sep = gtk.SeparatorMenuItem()
sep.show()
menu.add(sep)
def _get_menu_item(text, callback, data, sensitive=True):
item = gtk.MenuItem(text)
item.connect("activate", callback, data)
item.show()
item.set_sensitive(sensitive)
return item
def _get_radio_menu_item(text, callback, group):
item = gtk.RadioMenuItem(group, text, False)
item.show()
return item
def _get_image_menu_item(img, text, callback, data):
item = gtk.ImageMenuItem()
item.set_image(img)
item.connect("activate", callback, data)
item.set_always_show_image(True)
item.set_use_stock(False)
item.set_label(text)
item.show()
return item
# --------------------------------------------------- profile info gui
def get_profile_info_box(profile, show_description=True):
# Labels text
label_label = gtk.Label()
set_profile_info_labels_text(label_label, show_description)
# Values text
value_label = gtk.Label()
set_profile_info_values_text(profile, value_label, show_description)
# Create box
hbox = gtk.HBox()
hbox.pack_start(label_label, False, False, 0)
hbox.pack_start(value_label, True, True, 0)
return hbox
def get_profile_info_small_box(profile):
text = get_profile_info_text(profile)
label = gtk.Label(text)
hbox = gtk.HBox()
hbox.pack_start(label, False, False, 0)
return hbox
def get_profile_info_text(profile):
str_list = []
str_list.append(str(profile.width()))
str_list.append(" x ")
str_list.append(str(profile.height()))
str_list.append(", " + str(profile.display_aspect_num()))
str_list.append(":")
str_list.append(str(profile.display_aspect_den()))
str_list.append(", ")
if profile.progressive() == True:
str_list.append(_("Progressive"))
else:
str_list.append(_("Interlaced"))
str_list.append("\n")
str_list.append(_("Fps: ") + str(profile.fps()))
pix_asp = float(profile.sample_aspect_num()) / profile.sample_aspect_den()
pa_str = "%.2f" % pix_asp
str_list.append(", " + _("Pixel Aspect: ") + pa_str)
return ''.join(str_list)
def set_profile_info_labels_text(label, show_description):
str_list = []
if show_description:
str_list.append(_("Description:"))
str_list.append("\n")
str_list.append(_("Dimensions:"))
str_list.append("\n")
str_list.append(_("Frames per second:"))
str_list.append("\n")
str_list.append(_("Size:"))
str_list.append("\n")
str_list.append(_("Pixel aspect ratio: "))
str_list.append("\n")
str_list.append(_("Progressive:"))
label_label_text = ''.join(str_list)
label.set_text(label_label_text)
label.set_justify(gtk.JUSTIFY_LEFT)
def set_profile_info_values_text(profile, label, show_description):
str_list = []
if show_description:
str_list.append(profile.description())
str_list.append("\n")
str_list.append(str(profile.display_aspect_num()))
str_list.append(":")
str_list.append(str(profile.display_aspect_den()))
str_list.append("\n")
str_list.append(str(profile.fps()))
str_list.append("\n")
str_list.append(str(profile.width()))
str_list.append(" x ")
str_list.append(str(profile.height()))
str_list.append("\n")
pix_asp = float(profile.sample_aspect_num()) / profile.sample_aspect_den()
pa_str = "%.2f" % pix_asp
str_list.append(pa_str)
str_list.append("\n")
if profile.progressive() == True:
prog = _("Yes")
else:
prog = _("No")
str_list.append(prog)
value_label_text = ''.join(str_list)
label.set_text(value_label_text)
label.set_justify(gtk.JUSTIFY_LEFT)
class BigTCDisplay:
def __init__(self):
self.widget = CairoDrawableArea(170,
22,
self._draw)
self.font_desc = pango.FontDescription("Bitstream Vera Sans Mono Condensed 15")
#Draw consts
x = 2
y = 2
width = 166
height = 24
aspect = 1.0
corner_radius = height / 3.5
radius = corner_radius / aspect
degrees = M_PI / 180.0
self._draw_consts = (x, y, width, height, aspect, corner_radius, radius, degrees)
self.TEXT_X = 18
self.TEXT_Y = 1
def _draw(self, event, cr, allocation):
"""
Callback for repaint from CairoDrawableArea.
We get cairo contect and allocation.
"""
x, y, w, h = allocation
# Draw bg
cr.set_source_rgba(*gui.bg_color_tuple)
cr.rectangle(0, 0, w, h)
cr.fill()
# Draw round rect with gradient and stroke around for thin bezel
self._round_rect_path(cr)
cr.set_source_rgb(0.2, 0.2, 0.2)
cr.fill_preserve()
grad = cairo.LinearGradient (0, 0, 0, h)
for stop in BIG_TC_GRAD_STOPS:
grad.add_color_stop_rgba(*stop)
cr.set_source(grad)
cr.fill_preserve()
grad = cairo.LinearGradient (0, 0, 0, h)
for stop in BIG_TC_FRAME_GRAD_STOPS:
grad.add_color_stop_rgba(*stop)
cr.set_source(grad)
cr.set_line_width(1)
cr.stroke()
# Get current TIMELINE frame str
frame = PLAYER().tracktor_producer.frame()
frame_str = utils.get_tc_string(frame)
# Text
pango_context = pangocairo.CairoContext(cr)
layout = pango_context.create_layout()
layout.set_text(frame_str)
layout.set_font_description(self.font_desc)
pango_context.set_source_rgb(*TC_COLOR)#0.7, 0.7, 0.7)
pango_context.move_to(self.TEXT_X, self.TEXT_Y)
pango_context.update_layout(layout)
pango_context.show_layout(layout)
def _round_rect_path(self, cr):
x, y, width, height, aspect, corner_radius, radius, degrees = self._draw_consts
cr.new_sub_path()
cr.arc (x + width - radius, y + radius, radius, -90 * degrees, 0 * degrees)
cr.arc (x + width - radius, y + height - radius, radius, 0 * degrees, 90 * degrees)
cr.arc (x + radius, y + height - radius, radius, 90 * degrees, 180 * degrees)
cr.arc (x + radius, y + radius, radius, 180 * degrees, 270 * degrees)
cr.close_path ()
class MonitorTCDisplay:
"""
Mostly copy-pasted from BigTCDisplay, just enough different to make common inheritance
annoying.
"""
def __init__(self):
self.widget = CairoDrawableArea(94,
20,
self._draw)
self.font_desc = pango.FontDescription("Bitstream Vera Sans Mono Condensed 9")
#Draw consts
x = 2
y = 2
width = 90
height = 16
aspect = 1.0
corner_radius = height / 3.5
radius = corner_radius / aspect
degrees = M_PI / 180.0
self._draw_consts = (x, y, width, height, aspect, corner_radius, radius, degrees)
self._frame = 0
self.use_internal_frame = False
def set_frame(self, frame):
self._frame = frame # this is used in tools, editor window uses PLAYER frame
self.widget.queue_draw()
def _draw(self, event, cr, allocation):
"""
Callback for repaint from CairoDrawableArea.
We get cairo contect and allocation.
"""
x, y, w, h = allocation
# Draw bg
cr.set_source_rgb(*(gui.bg_color_tuple))
cr.rectangle(0, 0, w, h)
cr.fill()
# Draw round rect with gradient and stroke around for thin bezel
self._round_rect_path(cr)
cr.set_source_rgb(0.2, 0.2, 0.2)
cr.fill_preserve()
grad = cairo.LinearGradient (0, 0, 0, h)
for stop in BIG_TC_GRAD_STOPS:
grad.add_color_stop_rgba(*stop)
cr.set_source(grad)
cr.fill_preserve()
grad = cairo.LinearGradient (0, 0, 0, h)
for stop in BIG_TC_FRAME_GRAD_STOPS:
grad.add_color_stop_rgba(*stop)
cr.set_source(grad)
cr.set_line_width(1)
cr.stroke()
# Get current TIMELINE frame str
if self.use_internal_frame:
frame = self._frame
else:
frame = PLAYER().tracktor_producer.frame()
frame_str = utils.get_tc_string(frame)
# Text
pango_context = pangocairo.CairoContext(cr)
layout = pango_context.create_layout()
layout.set_text(frame_str)
layout.set_font_description(self.font_desc)
pango_context.set_source_rgb(0.7, 0.7, 0.7)
pango_context.move_to(8, 2)
pango_context.update_layout(layout)
pango_context.show_layout(layout)
def _round_rect_path(self, cr):
x, y, width, height, aspect, corner_radius, radius, degrees = self._draw_consts
cr.new_sub_path()
cr.arc (x + width - radius, y + radius, radius, -90 * degrees, 0 * degrees)
cr.arc (x + width - radius, y + height - radius, radius, 0 * degrees, 90 * degrees)
cr.arc (x + radius, y + height - radius, radius, 90 * degrees, 180 * degrees)
cr.arc (x + radius, y + radius, radius, 180 * degrees, 270 * degrees)
cr.close_path ()
class TimeLineLeftBottom:
def __init__(self):
self.widget = gtk.HBox()
self.update_gui()
def update_gui(self):
for child in self.widget.get_children():
self.widget.remove(child)
self.widget.pack_start(gtk.Label(), True, True)
if PROJECT().proxy_data.proxy_mode == appconsts.USE_PROXY_MEDIA:
proxy_img = gtk.image_new_from_file(respaths.IMAGE_PATH + "project_proxy.png")
self.widget.pack_start(proxy_img, False, False)
self.widget.show_all()
self.widget.queue_draw()
def get_gpl3_scroll_widget(size):
license_file = open(respaths.GPL_3_DOC)
license_text = license_file.read()
view = gtk.TextView()
view.set_sensitive(False)
view.set_pixels_above_lines(2)
view.set_left_margin(2)
view.set_wrap_mode(gtk.WRAP_WORD)
view.get_buffer().set_text(license_text)
sw = gtk.ScrolledWindow()
sw.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
sw.add(view)
sw.set_size_request(*size)
return sw
def get_translations_scroll_widget(size):
trans_file = open(respaths.TRANSLATIONS_DOC)
trans_text = trans_file.read()
view = gtk.TextView()
view.set_sensitive(False)
view.set_pixels_above_lines(2)
view.set_left_margin(2)
view.set_wrap_mode(gtk.WRAP_WORD)
view.get_buffer().set_text(trans_text)
sw = gtk.ScrolledWindow()
sw.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
sw.add(view)
sw.set_size_request(*size)
return sw
def get_track_counts_combo_and_values_list():
tracks_combo = gtk.combo_box_new_text()
tracks_combo.append_text(_("5 video, 4 audio"))
tracks_combo.append_text(_("4 video, 3 audio"))
tracks_combo.append_text(_("3 video, 2 audio"))
tracks_combo.append_text(_("2 video, 1 audio"))
tracks_combo.append_text(_("8 video, 1 audio"))
tracks_combo.append_text(_("1 video, 8 audio"))
tracks_combo.set_active(0)
tracks_combo_values_list = appconsts.TRACK_CONFIGURATIONS
return (tracks_combo, tracks_combo_values_list)
def get_markers_menu_launcher(callback, pixbuf):
m_launch = PressLaunch(callback, pixbuf)
return m_launch
def get_markers_popup_menu(event, callback):
seq = current_sequence()
markers_exist = len(seq.markers) != 0
menu = gtk.Menu()
if markers_exist:
for i in range(0, len(seq.markers)):
marker = seq.markers[i]
name, frame = marker
item_str = utils.get_tc_string(frame) + " " + name
menu.add(_get_menu_item(_(item_str), callback, str(i) ))
_add_separetor(menu)
else:
no_markers_item = _get_menu_item(_("No Markers"), callback, "dummy", False)
menu.add(no_markers_item)
_add_separetor(menu)
menu.add(_get_menu_item(_("Add Marker"), callback, "add" ))
del_item = _get_menu_item(_("Delete Marker"), callback, "delete", markers_exist==True)
menu.add(del_item)
del_all_item = _get_menu_item(_("Delete All Markers"), callback, "deleteall", markers_exist==True)
menu.add(del_all_item)
menu.popup(None, None, None, event.button, event.time)
def get_all_tracks_popup_menu(event, callback):
menu = gtk.Menu()
menu.add(_get_menu_item(_("Maximize Tracks"), callback, "max" ))
menu.add(_get_menu_item(_("Maximize Video Tracks"), callback, "maxvideo" ))
menu.add(_get_menu_item(_("Maximize Audio Tracks"), callback, "maxaudio" ))
_add_separetor(menu)
menu.add(_get_menu_item(_("Minimize Tracks"), callback, "min" ))
menu.popup(None, None, None, event.button, event.time)
def get_monitor_view_popupmenu(launcher, event, callback):
menu = gtk.Menu()
menu.add(_get_image_menu_item(gtk.image_new_from_file(
respaths.IMAGE_PATH + "program_view_2.png"), _("Image"), callback, 0))
menu.add(_get_image_menu_item(gtk.image_new_from_file(
respaths.IMAGE_PATH + "vectorscope.png"), _("Vectorscope"), callback, 1))
menu.add(_get_image_menu_item(gtk.image_new_from_file(
respaths.IMAGE_PATH + "rgbparade.png"), _("RGB Parade"), callback, 2))
menu.popup(None, None, None, event.button, event.time)
def get_mode_selector_popup_menu(launcher, event, callback):
menu = gtk.Menu()
menu.set_accel_group(gui.editor_window.accel_group)
menu_item = _get_image_menu_item(gtk.image_new_from_file(
respaths.IMAGE_PATH + "insertmove_cursor.png"), _("Insert"), callback, 0)
menu_item.set_accel_path("<Actions>/WindowActions/InsertMode")
menu.add(menu_item)
menu_item = _get_image_menu_item(gtk.image_new_from_file(
respaths.IMAGE_PATH + "overwrite_cursor.png"), _("Overwrite"), callback, 1)
menu_item.set_accel_path("<Actions>/WindowActions/OverMode")
menu.add(menu_item)
menu_item = _get_image_menu_item(gtk.image_new_from_file(
respaths.IMAGE_PATH + "oneroll_cursor.png"), _("Trim"), callback, 2)
menu_item.set_accel_path("<Actions>/WindowActions/OneRollMode")
menu.add(menu_item)
menu_item = _get_image_menu_item(gtk.image_new_from_file(
respaths.IMAGE_PATH + "tworoll_cursor.png"), _("Roll"), callback, 3)
menu_item.set_accel_path("<Actions>/WindowActions/TwoRollMode")
menu.add(menu_item)
menu_item = _get_image_menu_item(gtk.image_new_from_file(
respaths.IMAGE_PATH + "slide_cursor.png"), _("Slip"), callback, 4)
menu_item.set_accel_path("<Actions>/WindowActions/SlideMode")
menu.add(menu_item)
menu_item = _get_image_menu_item(gtk.image_new_from_file(
respaths.IMAGE_PATH + "multimove_cursor.png"), _("Spacer"), callback, 5)
menu_item.set_accel_path("<Actions>/WindowActions/MultiMode")
menu.add(menu_item)
menu.popup(None, None, None, event.button, event.time)
def get_file_filter_popup_menu(launcher, event, callback):
menu = gtk.Menu()
menu.set_accel_group(gui.editor_window.accel_group)
menu_item = _get_image_menu_item(gtk.image_new_from_file(
respaths.IMAGE_PATH + "show_all_files.png"), _("All Files"), callback, 0)
menu.add(menu_item)
menu_item = _get_image_menu_item(gtk.image_new_from_file(
respaths.IMAGE_PATH + "show_video_files.png"), _("Video Files"), callback, 1)
menu.add(menu_item)
menu_item = _get_image_menu_item(gtk.image_new_from_file(
respaths.IMAGE_PATH + "show_audio_files.png"), _("Audio Files"), callback, 2)
menu.add(menu_item)
menu_item = _get_image_menu_item(gtk.image_new_from_file(
respaths.IMAGE_PATH + "show_graphics_files.png"), _("Graphics Files"), callback, 3)
menu.add(menu_item)
menu_item = _get_image_menu_item(gtk.image_new_from_file(
respaths.IMAGE_PATH + "show_imgseq_files.png"), _("Image Sequences"), callback, 4)
menu.add(menu_item)
menu_item = _get_image_menu_item(gtk.image_new_from_file(
respaths.IMAGE_PATH + "show_pattern_producers.png"), _("Pattern Producers"), callback, 5)
menu.add(menu_item)
menu.popup(None, None, None, event.button, event.time)
class PressLaunch:
def __init__(self, callback, pixbuf, w=22, h=22):
self.widget = CairoDrawableArea(w,
h,
self._draw)
self.widget.press_func = self._press_event
self.callback = callback
self.pixbuf = pixbuf
self.pixbuf_x = 6
self.pixbuf_y = 6
def _draw(self, event, cr, allocation):
x, y, w, h = allocation
# Draw bg
cr.set_source_rgb(*gui.bg_color_tuple)
cr.rectangle(0, 0, w, h)
cr.fill()
cr.set_source_pixbuf(self.pixbuf, self.pixbuf_x, self.pixbuf_y)
cr.paint()
def _press_event(self, event):
self.callback(self.widget, event)
class ImageMenuLaunch(PressLaunch):
def __init__(self, callback, pixbuf_list, w=22, h=22):
PressLaunch.__init__(self, callback, pixbuf_list[0], w, h)
self.pixbuf_list = pixbuf_list
def set_pixbuf(self, pixbuf_index):
self.pixbuf = self.pixbuf_list[pixbuf_index]
self.widget.queue_draw()
class ToolSelector(ImageMenuLaunch):
def _draw(self, event, cr, allocation):
PressLaunch._draw(self, event, cr, allocation)
cr.move_to(27, 13)
cr.line_to(32, 18)
cr.line_to(37, 13)
cr.close_path()
cr.set_source_rgb(0, 0, 0)
cr.fill()
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module handles initializing and displaying audiomonitor tool.
"""
import cairo
import pygtk
pygtk.require('2.0');
import gtk
import glib
import mlt
import pango
import pangocairo
import time
import appconsts
from cairoarea import CairoDrawableArea
import editorpersistance
import editorstate
import mltrefhold
import guiutils
import utils
SLOT_W = 60
METER_SLOT_H = 458
CONTROL_SLOT_H = 300
Y_TOP_PAD = 12
# Dash pattern used to create "LED"s
DASH_INK = 2.0
DASH_SKIP = 1.0
DASHES = [DASH_INK, DASH_SKIP, DASH_INK, DASH_SKIP]
METER_LIGHTS = 143 #57
#METER_HEIGHT = METER_LIGHTS * DASH_INK + (METER_LIGHTS - 1) * DASH_SKIP
METER_HEIGHT = METER_LIGHTS * DASH_INK + (METER_LIGHTS - 1) * DASH_SKIP
METER_WIDTH = 10
# These are calculated using IEC_Scale function in MLT and correspond to level values received here
DB_IEC_MINUS_2 = 0.95
DB_IEC_MINUS_4 = 0.9
DB_IEC_MINUS_6 = 0.85
DB_IEC_MINUS_10 = 0.75
DB_IEC_MINUS_12 = 0.70
DB_IEC_MINUS_20 = 0.5
DB_IEC_MINUS_40 = 0.15
PEAK_FRAMES = 14
OVER_FRAMES = 30
# Colors
METER_BG_COLOR = (0.15, 0.15, 0.15)
OVERLAY_COLOR = (0.70, 0.70, 0.70) #utils.get_cairo_color_tuple_255_rgb(63, 145, 188)#59, 140, 174) #(0.7, 0.7, 1.0)
# Color gradient used to draw "LED" colors
rr, rg, rb = utils.get_cairo_color_tuple_255_rgb(219, 69, 69)
RED_1 = (0, rr, rg, rb, 1)
RED_2 = (1 - DB_IEC_MINUS_4 - 0.005, rr, rg, rb, 1)
YELLOW_1 = (1 - DB_IEC_MINUS_4 - 0.005 + 0.001, 1, 1, 0, 1)
YELLOW_2 = (1 - DB_IEC_MINUS_12, 1, 1, 0, 1)
gr, gg, gb = utils.get_cairo_color_tuple_255_rgb(86, 188, 137)
GREEN_1 = (1 - DB_IEC_MINUS_12 + 0.001, gr, gg, gb, 1)
GREEN_2 = (1, gr, gg, gb, 1)
LEFT_CHANNEL = "_audio_level.0"
RIGHT_CHANNEL = "_audio_level.1"
MONITORING_AVAILABLE = False
# GUI compoents displaying levels
_monitor_window = None
_master_volume_meter = None
_update_ticker = None
_level_filters = [] # 0 master, 1 - (len - 1) editable tracks
_audio_levels = [] # 0 master, 1 - (len - 1) editable tracks
def init(profile):
audio_level_filter = mlt.Filter(profile, "audiolevel")
global MONITORING_AVAILABLE
if audio_level_filter != None:
MONITORING_AVAILABLE = True
editorstate.audio_monitoring_available = True
else:
MONITORING_AVAILABLE = False
editorstate.audio_monitoring_available = False
# We want this to be always present when closing app or we'll need to handle it being missing.
global _update_ticker
_update_ticker = utils.Ticker(_audio_monitor_update, 0.04)
_update_ticker.start_ticker()
_update_ticker.stop_ticker()
def init_for_project_load():
# Monitor window is quaranteed to be closed
if _update_ticker.running:
_update_ticker.stop_ticker()
global _level_filters
_level_filters = None
_init_level_filters(False)
_update_ticker.start_ticker()
def close():
close_audio_monitor()
close_master_meter()
_update_ticker.stop_ticker()
def show_audio_monitor():
global _monitor_window
if _monitor_window != None:
return
_init_level_filters(True)
_monitor_window = AudioMonitorWindow()
global _update_ticker
if _update_ticker.running == False:
_update_ticker.start_ticker()
def close_audio_monitor():
global _monitor_window
if _monitor_window == None:
return
editorstate.PLAYER().stop_playback()
# We're using _monitor_window as a flag here so we need to set to _monitor_window = None
# to stop _audio_monitor_update running before destroying resources used by it
temp_window = _monitor_window
_monitor_window = None
_destroy_level_filters(True)
# Close and destroy window when gtk finds time to do it
glib.idle_add(_audio_monitor_destroy, temp_window)
def _audio_monitor_destroy(closed_monitor_window):
closed_monitor_window.set_visible(False)
closed_monitor_window.destroy()
return False
def get_master_meter():
_init_level_filters(False)
global _master_volume_meter, _update_ticker
_master_volume_meter = MasterVolumeMeter()
if _update_ticker.running == False:
_update_ticker.start_ticker()
align = gtk.Alignment(xalign=0.5, yalign=0.5, xscale=1.0, yscale=1.0)
align.add(_master_volume_meter.widget)
align.set_padding(3, 3, 3, 3)
frame = gtk.Frame()
frame.add(align)
frame.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
return frame
def close_master_meter():
global _master_volume_meter
if _master_volume_meter == None:
return
editorstate.PLAYER().stop_playback()
# To avoid crashes we can't actually lose widget object before everything is
# cleaned up well but _master_volume_meter == None is flag for doing audio updates so we must
# set that first
temp_meter = _master_volume_meter
_master_volume_meter = None
_destroy_level_filters(False)
# Close and destroy window when gtk finds time to do it
glib.idle_add(_master_meter_destroy, temp_meter)
def _master_meter_destroy(closed_master_meter):
closed_master_meter.widget.set_visible(False)
closed_master_meter.widget.destroy()
return False
def _init_level_filters(create_track_filters):
# We're attaching level filters only to MLT objects and adding nothing to python objects,
# so when Sequence is saved these filters will automatically be removed.
# Filters are not part of sequence.Sequence object because they just used for monitoring,
#
# Track/master gain values are persistant, they're also editing desitions
# and are therefore part of sequence.Sequence objects.
# Create levels filters array if it deosn't exist
global _level_filters
if _level_filters == None:
_level_filters = []
seq = editorstate.current_sequence()
# Init master level filter if it does not exist
if len(_level_filters) == 0:
_level_filters.append(_add_audio_level_filter(seq.tractor, seq.profile))
# Init track level filters if requested
if create_track_filters == True:
for i in range(1, len(seq.tracks) - 1):
_level_filters.append(_add_audio_level_filter(seq.tracks[i], seq.profile))
def _destroy_level_filters(destroy_track_filters=False):
global _level_filters, _audio_levels
# We need to be sure that audio level updates are stopped before
# detaching and destroying them
_update_ticker.stop_ticker()
#time.sleep(0.2)
# Detach filters
if len(_level_filters) != 0:
seq = editorstate.current_sequence()
# Only detach master filter if both GUI components destroyed
if _monitor_window == None and _master_volume_meter == None:
seq.tractor.detach(_level_filters[0])
# Track filters are onlty detached when this called from wondow close
if destroy_track_filters:
for i in range(1, len(seq.tracks) - 1):
seq.tracks[i].detach(_level_filters[i])
# Destroy unneeded filters
if _master_volume_meter == None and _monitor_window == None:
_level_filters = []
_audio_levels = []
elif _monitor_window == None:
_level_filters = [_level_filters[0]]
_audio_levels[0] = 0.0
if _master_volume_meter != None or _monitor_window != None:
_update_ticker.start_ticker()
def _add_audio_level_filter(producer, profile):
audio_level_filter = mlt.Filter(profile, "audiolevel")
mltrefhold.hold_ref(audio_level_filter)
producer.attach(audio_level_filter)
return audio_level_filter
def _audio_monitor_update():
# This is not called from gtk thread
if _monitor_window == None and _master_volume_meter == None:
return
gtk.gdk.threads_enter()
global _audio_levels
_audio_levels = []
for i in range(0, len(_level_filters)):
#print i
audio_level_filter = _level_filters[i]
l_val = _get_channel_value(audio_level_filter, LEFT_CHANNEL)
r_val = _get_channel_value(audio_level_filter, RIGHT_CHANNEL)
_audio_levels.append((l_val, r_val))
if _monitor_window != None:
_monitor_window.meters_area.widget.queue_draw()
if _master_volume_meter != None:
_master_volume_meter.canvas.queue_draw()
gtk.gdk.threads_leave()
def _get_channel_value(audio_level_filter, channel_property):
level_value = audio_level_filter.get(channel_property)
if level_value == None:
level_value = "0.0"
try:
level_float = float(level_value)
except Exception:
level_float = 0.0
return level_float
class AudioMonitorWindow(gtk.Window):
def __init__(self):
gtk.Window.__init__(self)
self.connect("delete-event", lambda w, e:close_audio_monitor())
seq = editorstate.current_sequence()
meters_count = 1 + (len(seq.tracks) - 2) # master + editable tracks
self.gain_controls = []
self.meters_area = MetersArea(meters_count)
gain_control_area = gtk.HBox(False, 0)
seq = editorstate.current_sequence()
for i in range(0, meters_count):
if i == 0:
name = _("Master")
gain = GainControl(name, seq, seq.tractor, True)
else:
name = utils.get_track_name(seq.tracks[i], seq)
gain = GainControl(name, seq, seq.tracks[i])
if i == 0:
tmp = gain
gain = gtk.EventBox()
gain.add(tmp)
bg_color = gtk.gdk.Color(red=0.8, green=0.8, blue=0.8)
if editorpersistance.prefs.dark_theme == True:
bg_color = gtk.gdk.Color(red=0.4, green=0.4, blue=0.4)
gain.modify_bg(gtk.STATE_NORMAL, bg_color)
self.gain_controls.append(gain)
gain_control_area.pack_start(gain, False, False, 0)
meters_frame = gtk.Frame()
meters_frame.add(self.meters_area.widget)
pane = gtk.VBox(False, 1)
pane.pack_start(meters_frame, True, True, 0)
pane.pack_start(gain_control_area, True, True, 0)
align = gtk.Alignment()
align.set_padding(12, 12, 4, 4)
align.add(pane)
# Set pane and show window
self.add(align)
self.set_title(_("Audio Mixer"))
self.show_all()
self.set_resizable(False)
self.set_keep_above(True) # Perhaps configurable later
class MetersArea:
def __init__(self, meters_count):
w = SLOT_W * meters_count
h = METER_SLOT_H
self.widget = CairoDrawableArea(w,
h,
self._draw)
self.audio_meters = [] # displays both l_Value and r_value
for i in range(0, meters_count):
meter = AudioMeter(METER_HEIGHT)
if i != meters_count - 1:
meter.right_channel.draw_dB = True
self.audio_meters.append(meter)
def _draw(self, event, cr, allocation):
x, y, w, h = allocation
cr.set_source_rgb(*METER_BG_COLOR)
cr.rectangle(0, 0, w, h)
cr.fill()
grad = cairo.LinearGradient (0, Y_TOP_PAD, 0, METER_HEIGHT + Y_TOP_PAD)
grad.add_color_stop_rgba(*RED_1)
grad.add_color_stop_rgba(*RED_2)
grad.add_color_stop_rgba(*YELLOW_1)
grad.add_color_stop_rgba(*YELLOW_2)
grad.add_color_stop_rgba(*GREEN_1)
grad.add_color_stop_rgba(*GREEN_2)
for i in range(0, len(_audio_levels)):
meter = self.audio_meters[i]
l_value, r_value = _audio_levels[i]
x = i * SLOT_W
meter.display_value(cr, x, l_value, r_value, grad)
class AudioMeter:
def __init__(self, height):
self.left_channel = ChannelMeter(height, "L")
self.right_channel = ChannelMeter(height, "R")
self.x_pad_l = 18 + 2
self.x_pad_r = SLOT_W / 2 + 6 - 2
self.meter_width = METER_WIDTH
def display_value(self, cr, x, value_left, value_right, grad):
cr.set_source(grad)
cr.set_dash(DASHES, 0)
cr.set_line_width(self.meter_width)
self.left_channel.display_value(cr, x + self.x_pad_l, value_left)
cr.set_source(grad)
cr.set_dash(DASHES, 0)
cr.set_line_width(self.meter_width)
self.right_channel.display_value(cr, x + self.x_pad_r, value_right)
class ChannelMeter:
def __init__(self, height, channel_text):
self.height = height
self.channel_text = channel_text
self.peak = 0.0
self.countdown = 0
self.draw_dB = False
self.dB_x_pad = 11
self.y_top_pad = Y_TOP_PAD
self.over_countdown = 0
def display_value(self, cr, x, value):
if value > 1.0:
self.over_countdown = OVER_FRAMES
top = self.get_meter_y_for_value(value)
if (self.height - top) < 5: # fix for meter y rounding for vol 0
top = self.height
cr.move_to(x, self.height + self.y_top_pad)
cr.line_to(x, top + self.y_top_pad)
cr.stroke()
if value > self.peak:
self.peak = value
self.countdown = PEAK_FRAMES
if self.peak > value:
if self.peak > 1.0:
self.peak = 1.0
cr.rectangle(x - METER_WIDTH / 2,
self.get_meter_y_for_value(self.peak) + DASH_SKIP * 2 + DASH_INK + 3, # this y is just empirism, works
METER_WIDTH,
DASH_INK)
cr.fill()
self.countdown = self.countdown - 1
if self.countdown <= 0:
self.peak = 0
if self.over_countdown > 0:
cr.set_source_rgb(1,0.6,0.6)
cr.move_to(x, 0)
cr.line_to(x + 4, 4)
cr.line_to(x, 8)
cr.line_to(x - 4, 4)
cr.close_path()
cr.fill()
self.over_countdown = self.over_countdown - 1
self.draw_channel_identifier(cr, x)
if self.draw_dB == True:
self.draw_value_line(cr, x, 1.0, "0", 7)
self.draw_value_line(cr, x, DB_IEC_MINUS_4,"-4", 4)
self.draw_value_line(cr, x, DB_IEC_MINUS_12, "-12", 1)
self.draw_value_line(cr, x, DB_IEC_MINUS_20, "-20", 1)
self.draw_value_line(cr, x, DB_IEC_MINUS_40, "-40", 1)
self.draw_value_line(cr, x, 0.0, u"\u221E", 5)
def get_meter_y_for_value(self, value):
y = self.get_y_for_value(value)
# Get pad for y value between "LED"s
dash_sharp_pad = y % (DASH_INK + DASH_SKIP)
# Round to nearest full "LED" using pad value
if dash_sharp_pad < ((DASH_INK + DASH_SKIP) / 2):
meter_y = y - dash_sharp_pad
else:
dash_sharp_pad = (DASH_INK + DASH_SKIP) - dash_sharp_pad
meter_y = y + dash_sharp_pad
return meter_y
def get_y_for_value(self, value):
return self.height - (value * self.height)
def draw_value_line(self, cr, x, value, val_text, x_fine_tune):
y = self.get_y_for_value(value)
self.draw_text(val_text, "Sans 8", cr, x + self.dB_x_pad + x_fine_tune, y - 8 + self.y_top_pad, OVERLAY_COLOR)
def draw_channel_identifier(self, cr, x):
self.draw_text(self.channel_text, "Sans Bold 8", cr, x - 4, self.height + 2 + self.y_top_pad, OVERLAY_COLOR)
def draw_text(self, text, font_desc, cr, x, y, color):
pango_context = pangocairo.CairoContext(cr)
layout = pango_context.create_layout()
layout.set_text(text)
desc = pango.FontDescription(font_desc)
layout.set_font_description(desc)
pango_context.set_source_rgb(*color)
pango_context.move_to(x, y)
pango_context.update_layout(layout)
pango_context.show_layout(layout)
class GainControl(gtk.Frame):
def __init__(self, name, seq, producer, is_master=False):
gtk.Frame.__init__(self)
self.seq = seq
self.producer = producer
self.is_master = is_master
if is_master:
gain_value = seq.master_audio_gain # tractor master
else:
gain_value = producer.audio_gain # track
gain_value = gain_value * 100
self.adjustment = gtk.Adjustment(value=gain_value, lower=0, upper=100, step_incr=1)
self.slider = gtk.VScale()
self.slider.set_adjustment(self.adjustment)
self.slider.set_size_request(SLOT_W - 10, CONTROL_SLOT_H - 105)
self.slider.set_inverted(True)
self.slider.connect("value-changed", self.gain_changed)
if is_master:
pan_value = seq.master_audio_pan
else:
pan_value = producer.audio_pan
if pan_value == appconsts.NO_PAN:
pan_value = 0.5 # center
pan_value = (pan_value - 0.5) * 200 # from range 0 - 1 to range -100 - 100
self.pan_adjustment = gtk.Adjustment(value=pan_value, lower=-100, upper=100, step_incr=1)
self.pan_slider = gtk.HScale()
self.pan_slider.set_adjustment(self.pan_adjustment)
self.pan_slider.connect("value-changed", self.pan_changed)
self.pan_button = gtk.ToggleButton(_("Pan"))
self.pan_button.connect("toggled", self.pan_active_toggled)
if pan_value == 0.0:
self.pan_slider.set_sensitive(False)
else:
self.pan_button.set_active(True)
self.pan_adjustment.set_value(pan_value) # setting button active sets value = 0, set correct value again
label = guiutils.bold_label(name)
vbox = gtk.VBox(False, 0)
vbox.pack_start(guiutils.get_pad_label(5,5), False, False, 0)
vbox.pack_start(label, False, False, 0)
vbox.pack_start(guiutils.get_pad_label(5,5), False, False, 0)
vbox.pack_start(self.slider, False, False, 0)
vbox.pack_start(self.pan_button, False, False, 0)
vbox.pack_start(self.pan_slider, False, False, 0)
vbox.pack_start(guiutils.get_pad_label(5,5), False, False, 0)
self.add(vbox)
self.set_size_request(SLOT_W, CONTROL_SLOT_H)
def gain_changed(self, slider):
gain = slider.get_value() / 100.0
if self.is_master == True:
self.seq.set_master_gain(gain)
else:
self.seq.set_track_gain(self.producer, gain)
def pan_active_toggled(self, widget):
self.pan_slider.set_value(0.0)
if widget.get_active():
self.pan_slider.set_sensitive(True)
self.seq.add_track_pan_filter(self.producer, 0.5)
if self.is_master:
self.seq.master_audio_pan = 0.5
else:
self.pan_slider.set_sensitive(False)
self.seq.remove_track_pan_filter(self.producer)
if self.is_master:
self.seq.master_audio_pan = appconsts.NO_PAN
def pan_changed(self, slider):
pan_value = (slider.get_value() + 100) / 200.0
if self.is_master:
self.seq.set_master_pan_value(pan_value)
else:
self.seq.set_track_pan_value(self.producer, pan_value)
class MasterVolumeMeter:
def __init__(self):
self.meter = AudioMeter(METER_HEIGHT + 40)
self.meter.x_pad_l = 6
self.meter.x_pad_r = 14
self.meter.right_channel.draw_dB = True
self.meter.right_channel.dB_x_pad = -14
self.meter.meter_width = 5
self.top_pad = 14
self.meter.right_channel.y_top_pad = self.top_pad
self.meter.left_channel.y_top_pad = self.top_pad
w = SLOT_W - 40
h = METER_SLOT_H + 2 + 40
self.canvas = CairoDrawableArea(w,
h,
self._draw)
self.widget = gtk.VBox(False, 0)
self.widget.pack_start(self.canvas, False, False, 0)
def _draw(self, event, cr, allocation):
x, y, w, h = allocation
cr.set_source_rgb(*METER_BG_COLOR)
cr.rectangle(0, 0, w, h)
cr.fill()
grad = cairo.LinearGradient (0, self.top_pad, 0, METER_HEIGHT + self.top_pad)
grad.add_color_stop_rgba(*RED_1)
grad.add_color_stop_rgba(*RED_2)
grad.add_color_stop_rgba(*YELLOW_1)
grad.add_color_stop_rgba(*YELLOW_2)
grad.add_color_stop_rgba(*GREEN_1)
grad.add_color_stop_rgba(*GREEN_2)
l_value, r_value = _audio_levels[0]
x = 0
self.meter.display_value(cr, x, l_value, r_value, grad)
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2014 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
mlt_objects = []
def hold_ref(mlt_obj):
mlt_objects.append(mlt_obj)
def print_objects():
global mlt_objects
print "len(mlt_objects):", len(mlt_objects)
def print_and_clear():
print_objects()
global mlt_objects
mlt_objects = []
| Python |
"""
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor 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 3 of the License, or
(at your option) any later version.
Flowblade Movie Editor 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 Flowblade Movie Editor. If not, see <http://www.gnu.org/licenses/>.
"""
"""
Module creates EditAction objects that have user input as input
and sequence state changes as output.
Edits, undos and redos are done by creating and calling methods on these
EditAction objects and placing them on the undo/redo stack.
"""
import audiowaveform
import appconsts
import compositeeditor
from editorstate import current_sequence
from editorstate import get_track
from editorstate import PLAYER
import mltfilters
import movemodes
import resync
import trimmodes
import undo
import updater
import utils
# GUI updates are turned off for example when doing resync action
do_gui_update = False
# ---------------------------------- atomic edit ops
def append_clip(track, clip, clip_in, clip_out):
"""
Affects MLT c-struct and python obj values.
"""
clip.clip_in = clip_in
clip.clip_out = clip_out
track.clips.append(clip) # py
track.append(clip, clip_in, clip_out) # mlt
resync.clip_added_to_timeline(clip, track)
def _insert_clip(track, clip, index, clip_in, clip_out):
"""
Affects MLT c-struct and python obj values.
"""
clip.clip_in = clip_in
clip.clip_out = clip_out
track.clips.insert(index, clip) # py
track.insert(clip, index, clip_in, clip_out) # mlt
resync.clip_added_to_timeline(clip, track)
def _insert_blank(track, index, length):
track.insert_blank(index, length - 1) # -1 MLT API says so
blank_clip = track.get_clip(index)
current_sequence().add_clip_attr(blank_clip)
blank_clip.clip_in = 0
blank_clip.clip_out = length - 1 # -1, end inclusive
blank_clip.is_blanck_clip = True
track.clips.insert(index, blank_clip)
def _remove_clip(track, index):
"""
Affects MLT c-struct and python obj values.
"""
track.remove(index)
clip = track.clips.pop(index)
updater.clip_removed_during_edit(clip)
resync.clip_removed_from_timeline(clip)
return clip
# -------------------------------- combined edit ops
def _cut(track, index, clip_cut_frame, clip, clip_copy):
"""
Does cut by removing clip and adding it and copy back
"""
_remove_clip(track, index)
second_out = clip.clip_out # save before insert
_insert_clip(track, clip, index, clip.clip_in, clip_cut_frame - 1)
_insert_clip(track, clip_copy, index + 1, clip_cut_frame, second_out)
def _cut_blank(track, index, clip_cut_frame, clip):
"""
Cuts a blank clip in two.
"""
_remove_clip(track, index)
clip_one_length = clip_cut_frame
clip_two_length = clip.clip_out - clip_cut_frame + 1 # +1 == cut frame part of this clip
track.insert_blank(index, clip_one_length - 1) # -1 MLT api says so
track.insert_blank(index + 1, clip_two_length - 1) # -1 MLT api says so
_add_blank_to_py(track, index, clip_one_length)
_add_blank_to_py(track, index + 1, clip_two_length)
def _add_blank_to_py(track, index, length):
"""
Adds clip data to python side structures for clip that
already exists in MLT data structures
"""
blank_clip = track.get_clip(index)
current_sequence().add_clip_attr(blank_clip)
blank_clip.clip_in = 0
blank_clip.clip_out = length - 1 # -1, end inclusive
blank_clip.is_blanck_clip = True
track.clips.insert(index, blank_clip)
return blank_clip
# --------------------------------- util methods
def _set_in_out(clip, c_in, c_out):
"""
Affects MLT c-struct and python obj values.
"""
clip.clip_in = c_in
clip.clip_out = c_out
clip.set_in_and_out(c_in, c_out)
def _clip_length(clip): # check if can be removed
return clip.clip_out - clip.clip_in + 1 # +1, end inclusive
def _frame_on_cut(clip, clip_frame):
if clip_frame == clip.clip_in:
return True
if clip_frame == clip.clip_out + 1: # + 1 out is inclusive
return True
return False
def _remove_trailing_blanks_undo(self):
for trailing_blank in self.trailing_blanks:
track_index, length = trailing_blank
track = current_sequence().tracks[track_index]
_insert_blank(track, track.count(), length)
def _remove_trailing_blanks_redo(self):
_remove_all_trailing_blanks(self)
def _remove_all_trailing_blanks(self=None):
if self != None:
self.trailing_blanks = []
for i in range(1, len(current_sequence().tracks) - 1): # -1 because hidden track, 1 because black track
try:
track = current_sequence().tracks[i]
last_clip_index = track.count() - 1
clip = track.clips[last_clip_index]
if clip.is_blanck_clip:
length = clip.clip_length()
_remove_clip(track, last_clip_index)
if self != None:
self.trailing_blanks.append((i, length))
except:
pass
def _create_clip_clone(clip):
if clip.media_type != appconsts.PATTERN_PRODUCER:
new_clip = current_sequence().create_file_producer_clip(clip.path)
else:
new_clip = current_sequence().create_pattern_producer(clip.create_data)
new_clip.name = clip.name
return new_clip
def _create_mute_volume_filter(seq):
return mltfilters.create_mute_volume_filter(seq)
def _do_clip_mute(clip, volume_filter):
mltfilters.do_clip_mute(clip, volume_filter)
def _do_clip_unmute(clip):
clip.detach(clip.mute_filter.mlt_filter)
clip.mute_filter = None
def _remove_consecutive_blanks(track, index):
lengths = []
while track.clips[index].is_blanck_clip:
lengths.append(track.clips[index].clip_length())
_remove_clip(track, index)
if index == len(track.clips):
break
return lengths
#------------------------------------------------------------- overwrite util methods
def _overwrite_cut_track(track, frame, add_cloned_filters=False):
"""
If frame is on an existing cut, then the method does nothing and returns tuple (-1, -1)
to signal that no cut was made.
If frame is in middle of clip or blank, then the method cuts that item in two
and returns tuple of in and out frames of the clip that was cut as they
were before the cut, for the purpose of having information to do undo later.
If cut was made it also clones fliters to new clip created by cut if requested.
"""
index = track.get_clip_index_at(frame)
clip = track.clips[index]
orig_in_out = (clip.clip_in, clip.clip_out)
clip_start_in_tline = track.clip_start(index)
clip_frame = frame - clip_start_in_tline + clip.clip_in
if not _frame_on_cut(clip, clip_frame):
if clip.is_blank():
add_clip = _cut_blank(track, index, clip_frame, clip)
else:
add_clip = _create_clip_clone(clip)
_cut(track, index, clip_frame, clip, add_clip)
if add_cloned_filters:
clone_filters = current_sequence().clone_filters(clip)
add_clip.filters = clone_filters
_attach_all(add_clip)
return orig_in_out
else:
return (-1, -1)
def _overwrite_cut_range_out(track, self):
# self is the EditAction object
# Cut at out point if not already on cut and out point inside track length
self.orig_out_clip = None
if track.get_length() > self.over_out:
clip_in, clip_out = _overwrite_cut_track(track, self.over_out, True)
self.out_clip_in = clip_in
self.out_clip_length = clip_out - clip_in + 1 # Cut blank can't be reconstructed with clip_in data as it is always 0 for blank, so we use this
if clip_in != -1: # if we did cut we'll need to restore the dut out clip
# which is the original clip because
orig_index = track.get_clip_index_at(self.over_out - 1)
self.orig_out_clip = track.clips[orig_index]
else:
self.out_clip_in = -1
def _overwrite_restore_in(track, moved_index, self):
# self is the EditAction object
in_clip = _remove_clip(track, moved_index - 1)
if not in_clip.is_blanck_clip:
_insert_clip(track, in_clip, moved_index - 1,
in_clip.clip_in, self.in_clip_out)
else: # blanks can't be resized, so put in new blank
_insert_blank(track, moved_index - 1, self.in_clip_out - in_clip.clip_in + 1)
self.removed_clips.pop(0)
def _overwrite_restore_out(track, moved_index, self):
# self is the EditAction object
# If moved clip/s were last in the track and were moved slightly
# forward and were still last in track after move
# this leaves a trailing black that has been removed and this will fail
try:
out_clip = _remove_clip(track, moved_index)
if len(self.removed_clips) > 0: # If overwrite was done inside single clip everything is already in order
if not out_clip.is_blanck_clip:
_insert_clip(track, self.orig_out_clip, moved_index,
self.out_clip_in, out_clip.clip_out)
else: # blanks can't be resized, so put in new blank
_insert_blank(track, moved_index, self.out_clip_length)
self.removed_clips.pop(-1)
except:
pass
#---------------------------------------------- EDIT ACTION
class EditAction:
"""
Packages together edit data and methods to make an undoable
change to sequence.
data - input is dict with named attributes that correspond
to usage in undo_func and redo_func
redo_func is written so that it can be called also when edit is first done
and do_edit() is called.
"""
def __init__(self, undo_func, redo_func, data):
# Functions that change state both ways.
self.undo_func = undo_func
self.redo_func = redo_func
# Grabs data as object members.
self.__dict__.update(data)
# Other then actual trim edits, attempting all edits exits active trimodes and enters <X>_NO_EDIT trim mode.
self.exit_active_trimmode_on_edit = True
# HACK!!!! Overwrite edits crash at redo(sometimes undo) when current frame inside
# affected area if consumer running.
# Remove when fixed in MLT.
self.stop_for_edit = False
self.turn_on_stop_for_edit = False # set true in redo_func for edits that need it
# NEEDED FOR TRIM CRASH HACK, REMOVE IF FIXED IN MLT
# Length of the blank on hidden track covering the whole seuqunce
# needs to be updated after every edit EXCEPT after trim edits which
# update the hidden track themselves and this flag "update_hidden_track" to False
self.update_hidden_track_blank = True
def do_edit(self):
if self.exit_active_trimmode_on_edit:
trimmodes.set_no_edit_trim_mode()
self.redo()
undo.register_edit(self)
if self.turn_on_stop_for_edit:
self.stop_for_edit = True
def undo(self):
PLAYER().stop_playback()
# HACK, see above.
if self.stop_for_edit:
PLAYER().consumer.stop()
movemodes.clear_selected_clips() # selection not valid after change in sequence
_remove_trailing_blanks_undo(self)
_consolidate_all_blanks_undo(self)
self.undo_func(self)
_remove_all_trailing_blanks(None)
resync.calculate_and_set_child_clip_sync_states()
# HACK, see above.
if self.stop_for_edit:
PLAYER().consumer.start()
if do_gui_update:
self._update_gui()
def redo(self):
PLAYER().stop_playback()
# HACK, see above.
if self.stop_for_edit:
PLAYER().consumer.stop()
movemodes.clear_selected_clips() # selection not valid after change in sequence
self.redo_func(self)
_consolidate_all_blanks_redo(self)
_remove_trailing_blanks_redo(self)
resync.calculate_and_set_child_clip_sync_states()
# HACK, see above.
if self.stop_for_edit:
PLAYER().consumer.start()
if do_gui_update:
self._update_gui()
def _update_gui(self):
updater.update_tline_scrollbar() # Slider needs to adjust to possily new program length.
# This REPAINTS TIMELINE as a side effect.
updater.update_kf_editor()
current_sequence().update_edit_tracks_length() # NEEDED FOR TRIM CRASH HACK, REMOVE IF FIXED
if self.update_hidden_track_blank:
current_sequence().update_trim_hack_blank_length() # NEEDED FOR TRIM CRASH HACK, REMOVE IF FIXED
PLAYER().display_inside_sequence_length(current_sequence().seq_len) # NEEDED FOR TRIM CRASH HACK, REMOVE IF FIXED
# ---------------------------------------------------- SYNC DATA
class SyncData:
"""
Captures sync between two clips, values filled at use sites.
"""
def __init__(self):
self.pos_offset = None
self.clip_in = None
self.clip_out = None
self.master_clip = None
self.master_inframe = None
self.master_audio_index = None # this does nothing? try to remove.
#-------------------- APPEND CLIP
# "track","clip","clip_in","clip_out"
# Appends clip to track
def append_action(data):
action = EditAction(_append_undo,_append_redo, data)
return action
def _append_undo(self):
self.clip = _remove_clip(self.track, len(self.track.clips) - 1)
def _append_redo(self):
self.clip.index = self.track.count()
append_clip(self.track, self.clip, self.clip_in, self.clip_out)
#----------------- REMOVE MULTIPLE CLIPS
# "track","from_index","to_index"
def remove_multiple_action(data):
action = EditAction(_remove_multiple_undo,_remove_multiple_redo, data)
return action
def _remove_multiple_undo(self):
clips_count = self.to_index + 1 - self.from_index # + 1 == to_index inclusive
for i in range(0, clips_count):
add_clip = self.clips[i]
index = self.from_index + i
_insert_clip(self.track, add_clip, index, add_clip.clip_in, \
add_clip.clip_out)
def _remove_multiple_redo(self):
self.clips = []
for i in range(self.from_index, self.to_index + 1):
removed_clip = _remove_clip(self.track, self.from_index)
self.clips.append(removed_clip)
#----------------- LIFT MULTIPLE CLIPS
# "track","from_index","to_index"
def lift_multiple_action(data):
action = EditAction(_lift_multiple_undo,_lift_multiple_redo, data)
action.blank_clip = None
return action
def _lift_multiple_undo(self):
# Remove blank
_remove_clip(self.track, self.from_index)
# Insert clips
clips_count = self.to_index + 1 - self.from_index # + 1 == to_index inclusive
for i in range(0, clips_count):
add_clip = self.clips[i]
index = self.from_index + i
_insert_clip(self.track, add_clip, index, add_clip.clip_in, \
add_clip.clip_out)
def _lift_multiple_redo(self):
# Remove clips
self.clips = []
removed_length = 0
for i in range(self.from_index, self.to_index + 1): # + 1 == to_index inclusive
removed_clip = _remove_clip(self.track, self.from_index)
self.clips.append(removed_clip)
removed_length += _clip_length(removed_clip)
# Insert blank
_insert_blank(self.track, self.from_index, removed_length)
#----------------- CUT CLIP
# "track","clip","index","clip_cut_frame"
# Cuts clip at frame by creating two clips and setting ins and outs.
def cut_action(data):
action = EditAction(_cut_undo,_cut_redo, data)
return action
def _cut_undo(self):
_remove_clip(self.track, self.index)
_remove_clip(self.track, self.index)
_insert_clip(self.track, self.clip, self.index, self.clip.clip_in, \
self.new_clip.clip_out)
def _cut_redo(self):
# Create new second clip if does not exist
if(not hasattr(self, "new_clip")):
self.new_clip = _create_clip_clone(self.clip)
_cut(self.track, self.index, self.clip_cut_frame, self.clip, \
self.new_clip)
#----------------- INSERT CLIP
# "track","clip","index","clip_in","clip_out"
# Inserts clip at index into track
def insert_action(data):
action = EditAction(_insert_undo,_insert_redo, data)
return action
def _insert_undo(self):
_remove_clip(self.track, self.index)
def _insert_redo(self):
_insert_clip(self.track, self.clip, self.index, self.clip_in, self.clip_out)
#----------------- 3 POINT OVERWRITE
# "track","clip", "clip_in","clip_out","in_index","out_index"
def three_point_overwrite_action(data):
action = EditAction(_three_over_undo, _three_over_redo, data)
return action
def _three_over_undo(self):
_remove_clip(self.track, self.in_index)
clips_count = self.out_index + 1 - self.in_index # + 1 == to_index inclusive
for i in range(0, clips_count):
add_clip = self.clips[i]
index = self.in_index + i
_insert_clip(self.track, add_clip, index, add_clip.clip_in, add_clip.clip_out)
def _three_over_redo(self):
# Remove and replace
self.clips = []
for i in range(self.in_index, self.out_index + 1): # + 1 == out_index inclusive
removed_clip = _remove_clip(self.track, i)
self.clips.append(removed_clip)
_insert_clip(self.track, self.clip, self.in_index, self.clip_in, self.clip_out)
#----------------- SYNC OVERWRITE
#"track","clip","clip_in","clip_out","frame"
def sync_overwrite_action(data):
action = EditAction(_sync_over_undo, _sync_over_redo, data)
return action
def _sync_over_undo(self):
# Remove overwrite clip
track = self.track
_remove_clip(track, self.in_index)
# Fix in clip and remove cut created clip if in was cut
if self.in_clip_out != -1:
in_clip = _remove_clip(track, self.in_index - 1)
copy_clip = _create_clip_clone(in_clip)
_insert_clip(track, copy_clip, self.in_index - 1,
in_clip.clip_in, self.in_clip_out)
self.removed_clips.pop(0) # The end half of insert cut
# Fix out clip and remove cut created clip if out was cut
if self.out_clip_in != -1:
try:
out_clip = _remove_clip(track, self.out_index)
copy_clip = _create_clip_clone(out_clip)
if len(self.removed_clips) > 0: # If overwrite was done inside single clip
# we don' need to put end half of out clip back in
_insert_clip(track, copy_clip, self.out_index,
self.out_clip_in, out_clip.clip_out)
self.removed_clips.pop(-1) # Front half of out clip
except:
pass
# Put back old clips
for i in range(0, len(self.removed_clips)):
clip = self.removed_clips[i];
_insert_clip(self.track, clip, self.in_index + i, clip.clip_in,
clip.clip_out)
def _sync_over_redo(self):
# Cut at in point if not already on cut
track = self.track
in_clip_in, in_clip_out = _overwrite_cut_track(track, self.frame)
self.in_clip_out = in_clip_out # out frame of the clip *previous* to overwritten clip after cut
self.over_out = self.frame + self.clip_out - self.clip_in + 1 # +1 out frame incl.
# If out point in track area we need to cut out point too
if track.get_length() > self.over_out:
out_clip_in, out_clip_out = _overwrite_cut_track(track, self.over_out)
self.out_clip_in = out_clip_in
else:
self.out_clip_in = -1
# Splice out clips in overwrite range
self.removed_clips = []
self.in_index = track.get_clip_index_at(self.frame)
self.out_index = track.get_clip_index_at(self.over_out)
for i in range(self.in_index, self.out_index):
removed_clip = _remove_clip(track, self.in_index)
self.removed_clips.append(removed_clip)
#------------------------------------- GAP APPEND
#"track","clip","clip_in","clip_out","frame"
def gap_append_action(data):
action = EditAction(_gap_append_undo, _gap_append_redo, data)
return action
def _gap_append_undo(self):
pass
def _gap_append_redo(self):
pass
#----------------- TWO_ROLL_TRIM
# "track","index","from_clip","to_clip","delta","edit_done_callback"
# "cut_frame"
def tworoll_trim_action(data):
action = EditAction(_tworoll_trim_undo,_tworoll_trim_redo, data)
action.exit_active_trimmode_on_edit = False
action.update_hidden_track_blank = False
return action
def _tworoll_trim_undo(self):
_remove_clip(self.track, self.index)
_remove_clip(self.track, self.index - 1)
if self.non_edit_side_blank == False:
_insert_clip(self.track, self.from_clip, self.index - 1, \
self.from_clip.clip_in, \
self.from_clip.clip_out - self.delta)
_insert_clip(self.track, self.to_clip, self.index, \
self.to_clip.clip_in - self.delta, \
self.to_clip.clip_out )
elif self.to_clip.is_blanck_clip:
_insert_clip(self.track, self.from_clip, self.index - 1, \
self.from_clip.clip_in, \
self.from_clip.clip_out - self.delta)
_insert_blank(self.track, self.index, self.to_length)
else: # from clip is blank
_insert_blank(self.track, self.index - 1, self.from_length)
_insert_clip(self.track, self.to_clip, self.index, \
self.to_clip.clip_in - self.delta, \
self.to_clip.clip_out )
def _tworoll_trim_redo(self):
_remove_clip(self.track, self.index)
_remove_clip(self.track, self.index - 1)
if self.non_edit_side_blank == False:
_insert_clip(self.track, self.from_clip, self.index - 1, \
self.from_clip.clip_in, \
self.from_clip.clip_out + self.delta)
_insert_clip(self.track, self.to_clip, self.index, \
self.to_clip.clip_in + self.delta, \
self.to_clip.clip_out )
elif self.to_clip.is_blanck_clip:
_insert_clip(self.track, self.from_clip, self.index - 1, \
self.from_clip.clip_in, \
self.from_clip.clip_out + self.delta)
self.to_length = self.to_clip.clip_out - self.to_clip.clip_in + 1 # + 1 out incl
_insert_blank(self.track, self.index, self.to_length - self.delta)
else: # from clip is blank
self.from_length = self.from_clip.clip_out - self.from_clip.clip_in + 1 # + 1 out incl
_insert_blank(self.track, self.index - 1, self.from_length + self.delta )
_insert_clip(self.track, self.to_clip, self.index, \
self.to_clip.clip_in + self.delta, \
self.to_clip.clip_out )
if self.first_do == True:
self.first_do = False
self.edit_done_callback(True, self.cut_frame, self.delta, self.track, self.to_side_being_edited)
#----------------- SLIDE_TRIM
# "track","clip","delta","index","first_do","first_do_callback","start_frame_being_viewed"
def slide_trim_action(data):
action = EditAction(_slide_trim_undo,_slide_trim_redo, data)
action.exit_active_trimmode_on_edit = False
action.update_hidden_track_blank = False
return action
def _slide_trim_undo(self):
_remove_clip(self.track, self.index)
_insert_clip(self.track, self.clip, self.index,
self.clip.clip_in - self.delta, self.clip.clip_out - self.delta)
def _slide_trim_redo(self):
_remove_clip(self.track, self.index)
_insert_clip(self.track, self.clip, self.index,
self.clip.clip_in + self.delta, self.clip.clip_out + self.delta)
# Reinit one roll trim
if self.first_do == True:
self.first_do = False
self.first_do_callback(self.track, self.clip, self.index, self.start_frame_being_viewed)
#-------------------- INSERT MOVE
# "track","insert_index","selected_range_in","selected_range_out"
# "move_edit_done_func"
# Splices out clips in range and splices them in at given index
def insert_move_action(data):
action = EditAction(_insert_move_undo,_insert_move_redo, data)
return action
def _insert_move_undo(self):
# remove clips
for i in self.clips:
_remove_clip(self.track, self.real_insert_index)
# insert clips
for i in range(0, len(self.clips)):
clip = self.clips[i]
_insert_clip(self.track, clip, self.selected_range_in + i, \
clip.clip_in, clip.clip_out )
self.move_edit_done_func(self.clips)
def _insert_move_redo(self):
self.clips = []
self.real_insert_index = self.insert_index
clips_length = self.selected_range_out - self.selected_range_in + 1
# if insert after range it is different when clips removed
if self.real_insert_index > self.selected_range_out:
self.real_insert_index -= clips_length
# remove and save clips
for i in range(0, clips_length):
removed_clip = _remove_clip(self.track, self.selected_range_in)
self.clips.append(removed_clip)
# insert clips
for i in range(0, clips_length):
clip = self.clips[i]
_insert_clip(self.track, clip, self.real_insert_index + i, \
clip.clip_in, clip.clip_out )
self.move_edit_done_func(self.clips)
# --------------------------------------- INSERT MULTIPLE
# "track","clips","index"
def insert_multiple_action(data):
action = EditAction(_insert_multiple_undo, _insert_multiple_redo, data)
return action
def _insert_multiple_undo(self):
for i in range(0, len(self.clips)):
_remove_clip(self.track, self.index)
def _insert_multiple_redo(self):
for i in range(0, len(self.clips)):
add_clip = self.clips[i]
index = self.index + i
_insert_clip(self.track, add_clip, index, add_clip.clip_in, add_clip.clip_out)
#-------------------- MULTITRACK INSERT MOVE
# "track","to_track","insert_index","selected_range_in","selected_range_out"
# "move_edit_done_func"
# Splices out clips in range and splices them in at given index
def multitrack_insert_move_action(data):
action = EditAction(_multitrack_insert_move_undo,_multitrack_insert_move_redo, data)
return action
def _multitrack_insert_move_undo(self):
# remove clips
for i in self.clips:
_remove_clip(self.to_track, self.insert_index)
# insert clips
for i in range(0, len(self.clips)):
clip = self.clips[i]
_insert_clip(self.track, clip, self.selected_range_in + i, \
clip.clip_in, clip.clip_out )
self.move_edit_done_func(self.clips)
def _multitrack_insert_move_redo(self):
self.clips = []
clips_length = self.selected_range_out - self.selected_range_in + 1
# remove clips
for i in range(0, clips_length):
removed_clip = _remove_clip(self.track, self.selected_range_in)
self.clips.append(removed_clip)
# insert clips
for i in range(0, clips_length):
clip = self.clips[i]
_insert_clip(self.to_track, clip, self.insert_index + i, \
clip.clip_in, clip.clip_out )
self.move_edit_done_func(self.clips)
#----------------- OVERWRITE MOVE
# "track","over_in","over_out","selected_range_in"
# "selected_range_out","move_edit_done_func"
# Lifts clips from track and overwrites part of track with them
def overwrite_move_action(data):
action = EditAction(_overwrite_move_undo, _overwrite_move_redo, data)
return action
def _overwrite_move_undo(self):
track = self.track
# Remove moved clips
moved_clips_count = self.selected_range_out - self.selected_range_in + 1 # + 1 == out inclusive
moved_index = track.get_clip_index_at(self.over_in)
for i in range(0, moved_clips_count):
_remove_clip(track, moved_index)
# Fix in clip and remove cut created clip if in was cut
if self.in_clip_out != -1:
_overwrite_restore_in(track, moved_index, self)
# Fix out clip and remove cut created clip if out was cut
if self.out_clip_in != -1:
_overwrite_restore_out(track, moved_index, self)
# Put back old clips
for i in range(0, len(self.removed_clips)):
clip = self.removed_clips[i]
_insert_clip(track, clip, moved_index + i, clip.clip_in,
clip.clip_out)
# Remove blank from lifted clip
# if moved clip/s were last in track, the clip were trying to remove
# has already been removed so this will fail
try:
_remove_clip(track, self.selected_range_in)
except:
pass
# Put back lifted clips
for i in range(0, len(self.moved_clips)):
clip = self.moved_clips[i];
_insert_clip(track, clip, self.selected_range_in + i, clip.clip_in,
clip.clip_out)
def _overwrite_move_redo(self):
self.moved_clips = []
track = self.track
# Lift moved clips and insert blank in their place
for i in range(self.selected_range_in, self.selected_range_out + 1): # + 1 == out inclusive
removed_clip = _remove_clip(track, self.selected_range_in)
self.moved_clips.append(removed_clip)
removed_length = self.over_out - self.over_in
_insert_blank(track, self.selected_range_in, removed_length)
# Find out if overwrite starts after or on track end and pad track with blanck if so.
if self.over_in >= track.get_length():
self.starts_after_end = True
gap = self.over_out - track.get_length()
_insert_blank(track, len(track.clips), gap)
else:
self.starts_after_end = False
# Cut at in point if not already on cut
clip_in, clip_out = _overwrite_cut_track(track, self.over_in)
self.in_clip_out = clip_out
# Cut at out point if not already on cut and out point inside track length
_overwrite_cut_range_out(track, self)
# Splice out clips in overwrite range
self.removed_clips = []
in_index = track.get_clip_index_at(self.over_in)
out_index = track.get_clip_index_at(self.over_out)
for i in range(in_index, out_index):
removed_clip = _remove_clip(track, in_index)
self.removed_clips.append(removed_clip)
# Insert overwrite clips
for i in range(0, len(self.moved_clips)):
clip = self.moved_clips[i]
_insert_clip(track, clip, in_index + i, clip.clip_in, clip.clip_out)
# HACK, see EditAction for details
self.turn_on_stop_for_edit = True
#----------------- MULTITRACK OVERWRITE MOVE
# "track","to_track","over_in","over_out","selected_range_in"
# "selected_range_out","move_edit_done_func"
# Lifts clips from track and overwrites part of track with them
def multitrack_overwrite_move_action(data):
action = EditAction(_multitrack_overwrite_move_undo, _multitrack_overwrite_move_redo, data)
return action
def _multitrack_overwrite_move_undo(self):
track = self.track
to_track = self.to_track
# Remove moved clips
moved_clips_count = self.selected_range_out - self.selected_range_in + 1 # + 1 == out inclusive
moved_index = to_track.get_clip_index_at(self.over_in)
for i in range(0, moved_clips_count):
_remove_clip(to_track, moved_index)
# Fix in clip and remove cut created clip if in was cut
if self.in_clip_out != -1:
_overwrite_restore_in(to_track, moved_index, self)
# Fix out clip and remove cut created clip if out was cut
if self.out_clip_in != -1:
_overwrite_restore_out(to_track, moved_index, self)
# Put back old clips
for i in range(0, len(self.removed_clips)):
clip = self.removed_clips[i];
_insert_clip(to_track, clip, moved_index + i, clip.clip_in,
clip.clip_out)
# Remove blank from lifted clip
# if moved clip/s were last in track, the clip were trying to remove
# has already been removed so this will fail
try:
_remove_clip(track, self.selected_range_in)
except:
pass
# Put back lifted clips
for i in range(0, len(self.moved_clips)):
clip = self.moved_clips[i];
_insert_clip(track, clip, self.selected_range_in + i, clip.clip_in,
clip.clip_out)
def _multitrack_overwrite_move_redo(self):
self.moved_clips = []
track = self.track
to_track = self.to_track
# Lift moved clips and insert blank
for i in range(self.selected_range_in, self.selected_range_out + 1): # + 1 == out inclusive
removed_clip = _remove_clip(track, self.selected_range_in) # THIS LINE BUGS SOMETIMES FIND OUT WHY
self.moved_clips.append(removed_clip)
removed_length = self.over_out - self.over_in
_insert_blank(track, self.selected_range_in, removed_length)
# Find out if overwrite starts after track end and pad track with blank if so
if self.over_in >= to_track.get_length():
self.starts_after_end = True
gap = self.over_out - to_track.get_length()
_insert_blank(to_track, len(to_track.clips), gap)
else:
self.starts_after_end = False
# Cut at in point if not already on cut
clip_in, clip_out = _overwrite_cut_track(to_track, self.over_in)
self.in_clip_out = clip_out
# Cut at out point if not already on cut
_overwrite_cut_range_out(to_track, self)
# Splice out clips in overwrite range
self.removed_clips = []
in_index = to_track.get_clip_index_at(self.over_in)
out_index = to_track.get_clip_index_at(self.over_out)
for i in range(in_index, out_index):
removed_clip = _remove_clip(to_track, in_index)
self.removed_clips.append(removed_clip)
# Insert overwrite clips
for i in range(0, len(self.moved_clips)):
clip = self.moved_clips[i]
_insert_clip(to_track, clip, in_index + i, clip.clip_in, clip.clip_out)
# HACK, see EditAction for details
self.turn_on_stop_for_edit = True
#-------------------------------------------- MULTI MOVE
# "multi_data", "edit_delta"
# self.multi_data is multimovemode.MultimoveData
def multi_move_action(data):
action = EditAction(_multi_move_undo, _multi_move_redo, data)
return action
def _multi_move_undo(self):
track_moved = self.multi_data.track_affected
tracks = current_sequence().tracks
for i in range(1, len(tracks) - 1):
if not track_moved[i - 1]:
continue
track = tracks[i]
edit_op = self.multi_data.track_edit_ops[i - 1]
trim_blank_index = self.multi_data.trim_blank_indexes[i - 1]
if edit_op == appconsts.MULTI_NOOP:
continue
elif edit_op == appconsts.MULTI_TRIM:
blank_length = track.clips[trim_blank_index].clip_length()
_remove_clip(track, trim_blank_index)
_insert_blank(track, trim_blank_index, blank_length - self.edit_delta)
elif edit_op == appconsts.MULTI_ADD_TRIM:
_remove_clip(track, trim_blank_index)
elif edit_op == appconsts.MULTI_TRIM_REMOVE:
if self.edit_delta != -self.multi_data.max_backwards:
_remove_clip(track, trim_blank_index)
_insert_blank(track, trim_blank_index, self.orig_length)
tracks_compositors = _get_tracks_compositors_list()
for i in range(1, len(tracks) - 1):
if not track_moved[i - 1]:
continue
track_comp = tracks_compositors[i - 1]
for comp in track_comp:
if comp.clip_in >= self.multi_data.first_moved_frame + self.edit_delta:
comp.move(-self.edit_delta)
def _multi_move_redo(self):
tracks = current_sequence().tracks
track_moved = self.multi_data.track_affected
# Move clips
for i in range(1, len(tracks) - 1):
if not track_moved[i - 1]:
continue
track = tracks[i]
edit_op = self.multi_data.track_edit_ops[i - 1]
trim_blank_index = self.multi_data.trim_blank_indexes[i - 1]
if edit_op == appconsts.MULTI_NOOP:
continue
elif edit_op == appconsts.MULTI_TRIM:
blank_length = track.clips[trim_blank_index].clip_length()
_remove_clip(track, trim_blank_index)
_insert_blank(track, trim_blank_index, blank_length + self.edit_delta)
elif edit_op == appconsts.MULTI_ADD_TRIM:
_insert_blank(track, trim_blank_index, self.edit_delta)
elif edit_op == appconsts.MULTI_TRIM_REMOVE:
self.orig_length = track.clips[trim_blank_index].clip_length()
_remove_clip(track, trim_blank_index)
if self.edit_delta != -self.multi_data.max_backwards:
_insert_blank(track, trim_blank_index, self.orig_length + self.edit_delta)
# Move compositors
tracks_compositors = _get_tracks_compositors_list()
for i in range(1, len(tracks) - 1):
if not track_moved[i - 1]:
continue
track_comp = tracks_compositors[i - 1]
for comp in track_comp:
if comp.clip_in >= self.multi_data.first_moved_frame:
comp.move(self.edit_delta)
def _get_tracks_compositors_list():
tracks_list = []
tracks = current_sequence().tracks
compositors = current_sequence().compositors
for track_index in range(1, len(tracks) - 1):
track_compositors = []
for j in range(0, len(compositors)):
comp = compositors[j]
if comp.transition.b_track == track_index:
track_compositors.append(comp)
tracks_list.append(track_compositors)
return tracks_list
#------------------ TRIM CLIP START
# "track","clip","index","delta","first_do"
# "undo_done_callback" <- THIS IS REALLY BADLY NAMED, IT SHOULD BE FIRST DO CALLBACK
# Trims start of clip
def trim_start_action(data):
action = EditAction(_trim_start_undo,_trim_start_redo, data)
action.exit_active_trimmode_on_edit = False
action.update_hidden_track_blank = False
return action
def _trim_start_undo(self):
_remove_clip(self.track, self.index)
_insert_clip(self.track, self.clip, self.index,
self.clip.clip_in - self.delta, self.clip.clip_out)
def _trim_start_redo(self):
_remove_clip(self.track, self.index)
_insert_clip(self.track, self.clip, self.index,
self.clip.clip_in + self.delta, self.clip.clip_out)
# Reinit one roll trim
if self.first_do == True:
self.first_do = False
self.undo_done_callback(self.track, self.index, True)
#------------------ TRIM CLIP END
# "track","clip","index","delta", "first_do"
# "undo_done_callback" <- THIS IS REALLY BADLY NAMED, IT SHOULD BE FIRST DO CALLBACK
# Trims end of clip
def trim_end_action(data):
action = EditAction(_trim_end_undo,_trim_end_redo, data)
action.exit_active_trimmode_on_edit = False
action.update_hidden_track_blank = False
return action
def _trim_end_undo(self):
_remove_clip(self.track, self.index)
_insert_clip(self.track, self.clip, self.index,
self.clip.clip_in, self.clip.clip_out - self.delta)
def _trim_end_redo(self):
_remove_clip(self.track, self.index)
_insert_clip(self.track, self.clip, self.index,
self.clip.clip_in, self.clip.clip_out + self.delta)
# Reinit one roll trim
if self.first_do == True:
self.first_do = False
self.undo_done_callback(self.track, self.index + 1, False)
#------------------ TRIM LAST CLIP END
# "track","clip","index","delta", "first_do"
# "undo_done_callback" <- THIS IS REALLY BADLY NAMED, IT SHOULD BE FIRST DO CALLBACK
def trim_last_clip_end_action(data):
action = EditAction(_trim_last_clip_end_undo,_trim_last_clip_end_redo, data)
action.exit_active_trimmode_on_edit = False
action.update_hidden_track_blank = False
return action
def _trim_last_clip_end_undo(self):
_remove_clip(self.track, self.index)
_insert_clip(self.track, self.clip, self.index,
self.clip.clip_in, self.clip.clip_out - self.delta)
def _trim_last_clip_end_redo(self):
_remove_clip(self.track, self.index)
_insert_clip(self.track, self.clip, self.index,
self.clip.clip_in, self.clip.clip_out + self.delta)
# Reinit one roll trim for
if self.first_do == True:
self.first_do = False
self.undo_done_callback(self.track)
#------------------- ADD FILTER
# "clip","filter_info","filter_edit_done_func"
# Adds filter to clip.
def add_filter_action(data):
action = EditAction(_add_filter_undo,_add_filter_redo, data)
return action
def _add_filter_undo(self):
self.clip.detach(self.filter_object.mlt_filter)
index = self.clip.filters.index(self.filter_object)
self.clip.filters.pop(index)
self.filter_edit_done_func(self.clip, len(self.clip.filters) - 1) # updates effect stack gui
def _add_filter_redo(self):
try: # is redo, fails for first
self.clip.attach(self.filter_object.mlt_filter)
self.clip.filters.append(self.filter_object)
except: # First do
self.filter_object = current_sequence().create_filter(self.filter_info)
self.clip.attach(self.filter_object.mlt_filter)
self.clip.filters.append(self.filter_object)
self.filter_edit_done_func(self.clip, len(self.clip.filters) - 1) # updates effect stack gui
#------------------- ADD MULTIPART FILTER
# "clip","filter_info","filter_edit_done_func"
# Adds filter to clip.
def add_multipart_filter_action(data):
action = EditAction(_add_multipart_filter_undo,_add_multipart_filter_redo, data)
return action
def _add_multipart_filter_undo(self):
self.filter_object.detach_all_mlt_filters(self.clip)
index = self.clip.filters.index(self.filter_object)
self.clip.filters.pop(index)
self.filter_edit_done_func(self.clip, len(self.clip.filters) - 1) # updates effect stack
def _add_multipart_filter_redo(self):
try: # if redo, fails for first
self.filter_object.attach_filters(self.clip)
self.clip.filters.append(self.filter_object)
except: # First do
self.filter_object = current_sequence().create_multipart_filter(self.filter_info, self.clip)
self.filter_object.attach_all_mlt_filters(self.clip)
self.clip.filters.append(self.filter_object)
self.filter_edit_done_func(self.clip, len(self.clip.filters) - 1) # updates effect stack
#------------------- REMOVE FILTER
# "clip","index","filter_edit_done_func"
# Adds filter to clip.
def remove_filter_action(data):
action = EditAction(_remove_filter_undo,_remove_filter_redo, data)
return action
def _remove_filter_undo(self):
_detach_all(self.clip)
try:
self.clip.filters.insert(self.index, self.filter_object)
except:
self.clip.filters.append(self.filter_object)
_attach_all(self.clip)
self.filter_edit_done_func(self.clip,self.index) # updates effect stack gui if needed
def _remove_filter_redo(self):
_detach_all(self.clip)
self.filter_object = self.clip.filters.pop(self.index)
_attach_all(self.clip)
self.filter_edit_done_func(self.clip, len(self.clip.filters) - 1)# updates effect stack gui
def _detach_all(clip):
mltfilters.detach_all_filters(clip)
def _attach_all(clip):
mltfilters.attach_all_filters(clip)
#------------------- REMOVE MULTIPLE FILTERS
# "clips"
# Adds filter to clip.
def remove_multiple_filters_action(data):
action = EditAction(_remove_multiple_filters_undo,_remove_multiple_filters_redo, data)
return action
def _remove_multiple_filters_undo(self):
for clip, clip_filters in zip(self.clips, self.clip_filters):
clip.filters = clip_filters
_attach_all(clip)
def _remove_multiple_filters_redo(self):
self.clip_filters = []
for clip in self.clips:
_detach_all(clip)
self.clip_filters.append(clip.filters)
clip.filters = []
updater.clear_clip_from_editors(clip)
# -------------------------------------- CLONE FILTERS
#"clip","clone_source_clip"
def clone_filters_action(data):
action = EditAction(_clone_filters_undo, _clone_filters_redo, data)
return action
def _clone_filters_undo(self):
_detach_all(self.clip)
self.clip.filters = self.old_filters
_attach_all(self.clip)
def _clone_filters_redo(self):
if not hasattr(self, "clone_filters"):
self.clone_filters = current_sequence().clone_filters(self.clone_source_clip)
self.old_filters = self.clip.filters
_detach_all(self.clip)
self.clip.filters = self.clone_filters
_attach_all(self.clip)
# -------------------------------------- ADD COMPOSITOR ACTION
# "origin_clip_id",in_frame","out_frame","compositor_type","a_track","b_track"
def add_compositor_action(data):
action = EditAction(_add_compositor_undo, _add_compositor_redo, data)
action.first_do = True
return action
def _add_compositor_undo(self):
current_sequence().remove_compositor(self.compositor)
current_sequence().restack_compositors()
# Hack!!! Some filters don't seem to handle setting compositors None (and the
# following gc) and crash, so we'll hold references to them forever.
#global old_compositors
#old_compositors.append(self.compositor)
compositeeditor.maybe_clear_editor(self.compositor)
self.compositor = None
def _add_compositor_redo(self):
self.compositor = current_sequence().create_compositor(self.compositor_type)
self.compositor.transition.set_tracks(self.a_track, self.b_track)
self.compositor.set_in_and_out(self.in_frame, self.out_frame)
self.compositor.origin_clip_id = self.origin_clip_id
# Compositors are recreated continually in sequnece.restack_compositors() and cannot be identified for undo/redo using object identity
# so these ids must be preserved for all succesive versions of a compositor
if self.first_do == True:
self.destroy_id = self.compositor.destroy_id
self.first_do = False
else:
self.compositor.destroy_id = self.destroy_id
current_sequence().add_compositor(self.compositor)
current_sequence().restack_compositors()
compositeeditor.set_compositor(self.compositor)
# -------------------------------------- DELETE COMPOSITOR ACTION
# "compositor"
def delete_compositor_action(data):
action = EditAction(_delete_compositor_undo, _delete_compositor_redo, data)
action.first_do = True
return action
def _delete_compositor_undo(self):
old_compositor = self.compositor
self.compositor = current_sequence().create_compositor(old_compositor.type_id)
self.compositor.clone_properties(old_compositor)
self.compositor.set_in_and_out(old_compositor.clip_in, old_compositor.clip_out)
self.compositor.transition.set_tracks(old_compositor.transition.a_track, old_compositor.transition.b_track)
current_sequence().add_compositor(self.compositor)
current_sequence().restack_compositors()
compositeeditor.set_compositor(self.compositor)
def _delete_compositor_redo(self):
# Compositors are recreated continually in sequnece.restack_compositors() and cannot be identified for undo/redo using object identity
# so these ids must be preserved for all succesive versions of a compositor.
if self.first_do == True:
self.destroy_id = self.compositor.destroy_id
self.first_do = False
else:
self.compositor = current_sequence().get_compositor_for_destroy_id(self.destroy_id)
current_sequence().remove_compositor(self.compositor)
current_sequence().restack_compositors()
# Hack!!! Some filters don't seem to handle setting compositors None (and the
# following gc) and crash, so we'll hold references to them forever.
#global old_compositors
#old_compositors.append(self.compositor)
compositeeditor.maybe_clear_editor(self.compositor)
#--------------------------------------------------- MOVE COMPOSITOR
# "compositor","clip_in","clip_out"
def move_compositor_action(data):
action = EditAction(_move_compositor_undo, _move_compositor_redo, data)
action.first_do = True
return action
def _move_compositor_undo(self):
move_compositor = current_sequence().get_compositor_for_destroy_id(self.destroy_id)
move_compositor.set_in_and_out(self.orig_in, self.orig_out)
compositeeditor.set_compositor(self.compositor)
def _move_compositor_redo(self):
# Compositors are recreated continually in sequence.restack_compositors() and cannot be identified for undo/redo using object identity
# so these ids must be preserved for all succesive versions of a compositor.
if self.first_do == True:
self.destroy_id = self.compositor.destroy_id
self.orig_in = self.compositor.clip_in
self.orig_out = self.compositor.clip_out
self.first_do = False
move_compositor = current_sequence().get_compositor_for_destroy_id(self.destroy_id)
move_compositor.set_in_and_out(self.clip_in, self.clip_out)
compositeeditor.set_compositor(self.compositor)
#----------------- AUDIO SPLICE
# "parent_clip", "audio_clip", "track"
def audio_splice_action(data):
action = EditAction(_audio_splice_undo, _audio_splice_redo, data)
return action
def _audio_splice_undo(self):
to_track = self.to_track
# Remove add audio clip
in_index = to_track.get_clip_index_at(self.over_in)
_remove_clip(to_track, in_index)
# Fix in clip and remove cut created clip if in was cut
if self.in_clip_out != -1:
in_clip = _remove_clip(to_track, in_index - 1)
_insert_clip(to_track, in_clip, in_index - 1,
in_clip.clip_in, self.in_clip_out)
self.removed_clips.pop(0)
# Fix out clip and remove cut created clip if out was cut
if self.out_clip_in != -1:
# If moved clip/s were last in the track and were moved slightly
# forward and were still last in track after move
# this leaves a trailing black that has been removed and this will fail
try:
out_clip = _remove_clip(to_track, in_index)
if len(self.removed_clips) > 0: # If overwrite was done inside single clip everything is already in order
_insert_clip(to_track, out_clip, in_index,
self.out_clip_in, out_clip.clip_out)
self.removed_clips.pop(-1)
except:
pass
# Put back old clips
for i in range(0, len(self.removed_clips)):
clip = self.removed_clips[i];
_insert_clip(to_track, clip, in_index + i, clip.clip_in,
clip.clip_out)
_do_clip_unmute(self.parent_clip)
#_remove_trailing_blanks(to_track)
def _audio_splice_redo(self):
# Get shorter name for readability
to_track = self.to_track
# Find out if overwrite starts after track end and pad track with blanck if so.
if self.over_in >= to_track.get_length():
self.starts_after_end = True
gap = self.over_out - to_track.get_length()
_insert_blank(to_track, len(to_track.clips), gap)
else:
self.starts_after_end = False
# Cut at in frame of overwrite range.
clip_in, clip_out = _overwrite_cut_track(to_track, self.over_in)
self.in_clip_out = clip_out
# Cut at out frame of overwrite range
if to_track.get_length() > self.over_out:
clip_in, clip_out = _overwrite_cut_track(to_track, self.over_out)
self.out_clip_in = clip_in
else:
self.out_clip_in = -1
# Splice out clips in overwrite range
self.removed_clips = []
in_index = to_track.get_clip_index_at(self.over_in)
out_index = to_track.get_clip_index_at(self.over_out)
for i in range(in_index, out_index):
self.removed_clips.append(_remove_clip(to_track, in_index))
# Insert audio clip
_insert_clip(to_track, self.audio_clip, in_index, self.parent_clip.clip_in, self.parent_clip.clip_out)
filter = _create_mute_volume_filter(current_sequence())
_do_clip_mute(self.parent_clip, filter)
# ------------------------------------------------- RESYNC ALL
# No input data
def resync_all_action(data):
action = EditAction(_resync_all_undo, _resync_all_redo, data)
return action
def _resync_all_undo(self):
self.actions.reverse()
for action in self.actions:
action.undo_func(action)
self.actions.reverse()
def _resync_all_redo(self):
if hasattr(self, "actions"):
# Actions have already been created, this is redo
for action in self.actions:
action.redo_func(action)
return
resync_data = resync.get_resync_data_list()
self.actions = _create_and_do_sync_actions_list(resync_data)
# ------------------------------------------------- RESYNC SOME CLIPS
# "clips"
def resync_some_clips_action(data):
action = EditAction(_resync_some_clips_undo, _resync_some_clips_redo, data)
return action
def _resync_some_clips_undo(self):
self.actions.reverse()
for action in self.actions:
action.undo_func(action)
self.actions.reverse()
def _resync_some_clips_redo(self):
if hasattr(self, "actions"):
# Actions have already been created, this is redo
for action in self.actions:
action.redo_func(action)
return
resync_data = resync.get_resync_data_list_for_clip_list(self.clips)
self.actions = _create_and_do_sync_actions_list(resync_data)
def _create_and_do_sync_actions_list(resync_data_list):
# input is list tuples list (clip, track, index, pos_off)
actions = []
for clip_data in resync_data_list:
clip, track, index, pos_offset = clip_data
# If we're in sync, do nothing
if pos_offset == clip.sync_data.pos_offset:
continue
# Get new in and out frames for clip
diff = pos_offset - clip.sync_data.pos_offset
over_in = track.clip_start(index) - diff
over_out = over_in + (clip.clip_out - clip.clip_in + 1)
data = {"track":track,
"over_in":over_in,
"over_out":over_out,
"selected_range_in":index,
"selected_range_out":index,
"move_edit_done_func":None}
action = overwrite_move_action(data)
actions.append(action)
action.redo_func(action)
return actions
# ------------------------------------------------- RESYNC CLIP SEQUENCE
# "clips"
def resync_clips_sequence_action(data):
action = EditAction(_resync_clips_sequence_undo, _resync_clips_sequence_redo, data)
return action
def _resync_clips_sequence_undo(self):
if self.sync_action != None:
self.sync_action.undo_func(self.sync_action)
def _resync_clips_sequence_redo(self):
resync_data = resync.get_resync_data_list_for_clip_list(self.clips)
clip, track, index, pos_offset = resync_data[0]
# If we're in sync, do nothing
if pos_offset == clip.sync_data.pos_offset:
self.sync_action = None
else:
# Get new in and out frames for clips
diff = pos_offset - clip.sync_data.pos_offset
over_in = track.clip_start(index) - diff
clip_last, track, index_last, pos_offset = resync_data[-1]
last_over_in = track.clip_start(index_last) - diff
over_out = last_over_in + (clip_last.clip_out - clip_last.clip_in + 1)
# Create, do and sacve edit action.
data = {"track":track,
"over_in":over_in,
"over_out":over_out,
"selected_range_in":index,
"selected_range_out":index_last,
"move_edit_done_func":None}
action = overwrite_move_action(data)
action.redo_func(action)
self.sync_action = action
# ------------------------------------------------- SET SYNC
# "child_index","child_track","parent_index","parent_track"
def set_sync_action(data):
action = EditAction(_set_sync_undo, _set_sync_redo, data)
return action
def _set_sync_undo(self):
# Get clips
child_clip = self.child_track.clips[self.child_index]
# Clear child sync data
child_clip.sync_data = None
# Clear resync data
resync.clip_sync_cleared(child_clip)
def _set_sync_redo(self):
# Get clips
child_clip = self.child_track.clips[self.child_index]
parent_clip = get_track(current_sequence().first_video_index).clips[self.parent_index]
# Get offset
child_clip_start = self.child_track.clip_start(self.child_index) - child_clip.clip_in
parent_clip_start = self.parent_track.clip_start(self.parent_index) - parent_clip.clip_in
pos_offset = child_clip_start - parent_clip_start
# Set sync data
child_clip.sync_data = SyncData()
child_clip.sync_data.pos_offset = pos_offset
child_clip.sync_data.master_clip = parent_clip
child_clip.sync_data.sync_state = appconsts.SYNC_CORRECT
resync.clip_added_to_timeline(child_clip, self.child_track)
# ------------------------------------------------- CLEAR SYNC
# "child_clip","child_track"
def clear_sync_action(data):
action = EditAction(_clear_sync_undo, _clear_sync_redo, data)
return action
def _clear_sync_undo(self):
# Reset child sync data
self.child_clip.sync_data = self.sync_data
# Save data resync data for doing resyncs and sync state gui updates
resync.clip_added_to_timeline(self.child_clip, self.child_track)
def _clear_sync_redo(self):
# Save sync data
self.sync_data = self.child_clip.sync_data
# Clear child sync data
self.child_clip.sync_data = None
# Claer resync data
resync.clip_sync_cleared(self.child_clip)
# --------------------------------------- MUTE CLIP
# "clip"
def mute_clip(data):
action = EditAction(_mute_clip_undo,_mute_clip_redo, data)
return action
def _mute_clip_undo(self):
_do_clip_unmute(self.clip)
def _mute_clip_redo(self):
mute_filter = _create_mute_volume_filter(current_sequence())
_do_clip_mute(self.clip, mute_filter)
# --------------------------------------- UNMUTE CLIP
# "clip"
def unmute_clip(data):
action = EditAction(_unmute_clip_undo,_unmute_clip_redo, data)
return action
def _unmute_clip_undo(self):
mute_filter = _create_mute_volume_filter(current_sequence())
_do_clip_mute(self.clip, mute_filter)
def _unmute_clip_redo(self):
_do_clip_unmute(self.clip)
# ----------------------------------------- TRIM END OVER BLANKS
#"track","clip","clip_index"
def trim_end_over_blanks(data):
action = EditAction(_trim_end_over_blanks_undo, _trim_end_over_blanks_redo, data)
action.exit_active_trimmode_on_edit = False
action.update_hidden_track_blank = False
return action
def _trim_end_over_blanks_undo(self):
# put back blanks
total_length = 0
for i in range(0, len(self.removed_lengths)):
length = self.removed_lengths[i]
_insert_blank(self.track, self.clip_index + 1 + i, length)
total_length = total_length + length
# trim clip
_remove_clip(self.track, self.clip_index)
_insert_clip(self.track, self.clip, self.clip_index, self.clip.clip_in, self.clip.clip_out - total_length)
def _trim_end_over_blanks_redo(self):
# Remove blanks
self.removed_lengths = _remove_consecutive_blanks(self.track, self.clip_index + 1) # +1, we're streching clip over blank are starting at NEXT index
total_length = 0
for length in self.removed_lengths:
total_length = total_length + length
# trim clip
_remove_clip(self.track, self.clip_index)
_insert_clip(self.track, self.clip, self.clip_index, self.clip.clip_in, self.clip.clip_out + total_length)
# ----------------------------------------- TRIM START OVER BLANKS
# "track","clip","blank_index"
def trim_start_over_blanks(data):
action = EditAction(_trim_start_over_blanks_undo, _trim_start_over_blanks_redo, data)
action.exit_active_trimmode_on_edit = False
action.update_hidden_track_blank = False
return action
def _trim_start_over_blanks_undo(self):
# trim clip
_remove_clip(self.track, self.blank_index)
_insert_clip(self.track, self.clip, self.blank_index, self.clip.clip_in + self.total_length, self.clip.clip_out)
# put back blanks
for i in range(0, len(self.removed_lengths)):
length = self.removed_lengths[i]
_insert_blank(self.track, self.blank_index + i, length)
def _trim_start_over_blanks_redo(self):
# Remove blanks
self.removed_lengths = _remove_consecutive_blanks(self.track, self.blank_index)
self.total_length = 0
for length in self.removed_lengths:
self.total_length = self.total_length + length
# trim clip
_remove_clip(self.track, self.blank_index)
_insert_clip(self.track, self.clip, self.blank_index, self.clip.clip_in - self.total_length, self.clip.clip_out)
# ---------------------------------------- CONSOLIDATE SELECTED BLANKS
# "track","index"
def consolidate_selected_blanks(data):
action = EditAction(_consolidate_selected_blanks_undo,_consolidate_selected_blanks_redo, data)
return action
def _consolidate_selected_blanks_undo(self):
_remove_clip(self.track, self.index)
for i in range(0, len(self.removed_lengths)):
length = self.removed_lengths[i]
_insert_blank(self.track, self.index + i, length)
def _consolidate_selected_blanks_redo(self):
self.removed_lengths = _remove_consecutive_blanks(self.track, self.index)
total_length = 0
for length in self.removed_lengths:
total_length = total_length + length
_insert_blank(self.track, self.index, total_length)
#----------------------------------- CONSOLIDATE ALL BLANKS
def consolidate_all_blanks(data):
action = EditAction(_consolidate_all_blanks_undo,_consolidate_all_blanks_redo, data)
return action
def _consolidate_all_blanks_undo(self):
self.consolidate_actions.reverse()
for c_action in self.consolidate_actions:
track, index, removed_lengths = c_action
_remove_clip(track, index)
for i in range(0, len(removed_lengths)):
length = removed_lengths[i]
_insert_blank(track, index + i, length)
def _consolidate_all_blanks_redo(self):
self.consolidate_actions = []
for i in range(1, len(current_sequence().tracks) - 1): # -1 because hidden track, 1 because black track
track = current_sequence().tracks[i]
consolidaded_indexes = []
try_do_next = True
while(try_do_next == True):
if len(track.clips) == 0:
try_do_next = False
for i in range(0, len(track.clips)):
if i == len(track.clips) - 1:
try_do_next = False
clip = track.clips[i]
if clip.is_blanck_clip == False:
continue
try:
consolidaded_indexes.index(i)
continue
except:
pass
# Now consolidate from clip in index i
consolidaded_indexes.append(i)
removed_lengths = _remove_consecutive_blanks(track, i)
total_length = 0
for length in removed_lengths:
total_length = total_length + length
_insert_blank(track, i, total_length)
self.consolidate_actions.append((track, i, removed_lengths))
break
#----------------- RANGE OVERWRITE
# "track","clip","clip_in","clip_out","mark_in_frame","mark_out_frame"
def range_overwrite_action(data):
action = EditAction(_range_over_undo, _range_over_redo, data)
return action
def _range_over_undo(self):
_remove_clip(self.track, self.track_extract_data.in_index)
_track_put_back_range(self.mark_in_frame,
self.track,
self.track_extract_data)
def _range_over_redo(self):
self.track_extract_data = _track_extract_range(self.mark_in_frame,
self.mark_out_frame,
self.track)
_insert_clip(self.track,
self.clip,
self.track_extract_data.in_index,
self.clip_in,
self.clip_out)
# HACK, see EditAction for details
self.turn_on_stop_for_edit = True
#------------------- ADD CENTERED TRANSITION
# "transition_clip","transition_index", "from_clip","to_clip","track","from_in","to_out"
def add_centered_transition_action(data):
action = EditAction(_add_centered_transition_undo, _add_centered_transition_redo, data)
return action
def _add_centered_transition_undo(self):
index = self.transition_index
track = self.track
from_clip = self.from_clip
to_clip = self.to_clip
for i in range(0, 3): # from, trans, to
_remove_clip(track, index - 1)
_insert_clip(track, from_clip, index - 1,
from_clip.clip_in, self.orig_from_clip_out)
_insert_clip(track, to_clip, index,
self.orig_to_clip_in, to_clip.clip_out)
def _add_centered_transition_redo(self):
# get shorter refs
transition_clip = self.transition_clip
index = self.transition_index
track = self.track
from_clip = self.from_clip
to_clip = self.to_clip
# Save from and to clip in/out points before adding transition
self.orig_from_clip_out = from_clip.clip_out
self.orig_to_clip_in = to_clip.clip_in
# Shorten from clip
_remove_clip(track, index - 1)
_insert_clip(track, from_clip, index - 1,
from_clip.clip_in, self.from_in) # self.from_in == transition start on from clip
# Shorten to clip
_remove_clip(track, index)
_insert_clip(track, to_clip, index,
self.to_out + 1, to_clip.clip_out) # self.to_out == transition end on to clip
# + 1 == because frame is part of inserted transition
# Insert transition
_insert_clip(track, transition_clip,
self.transition_index, 1, # first frame is dropped as it is 100% from clip
transition_clip.get_length() - 1)
# -------------------------------------------------------- RENDERED FADE IN
# "fade_clip", "clip_index", "track", "length"
def add_rendered_fade_in_action(data):
action = EditAction(_add_rendered_fade_in_undo, _add_rendered_fade_in_redo, data)
return action
def _add_rendered_fade_in_undo(self):
_remove_clip(self.track, self.index)
_remove_clip(self.track, self.index)
_insert_clip(self.track, self.orig_clip, self.index, self.orig_clip_in, self.orig_clip.clip_out)
def _add_rendered_fade_in_redo(self):
self.orig_clip = _remove_clip(self.track, self.index)
self.orig_clip_in = self.orig_clip.clip_in
_insert_clip(self.track, self.fade_clip, self.index, 0, self.length - 1)
_insert_clip(self.track, self.orig_clip, self.index + 1, self.orig_clip.clip_in + self.length, self.orig_clip.clip_out)
# -------------------------------------------------------- RENDERED FADE OUT
# "fade_clip", "clip_index", "track", "length"
def add_rendered_fade_out_action(data):
action = EditAction(_add_rendered_fade_out_undo, _add_rendered_fade_out_redo, data)
return action
def _add_rendered_fade_out_undo(self):
_remove_clip(self.track, self.index)
_remove_clip(self.track, self.index)
_insert_clip(self.track, self.orig_clip, self.index, self.orig_clip.clip_in, self.orig_clip_out)
def _add_rendered_fade_out_redo(self):
self.orig_clip = _remove_clip(self.track, self.index)
self.orig_clip_out = self.orig_clip.clip_out
_insert_clip(self.track, self.orig_clip, self.index, self.orig_clip.clip_in, self.orig_clip.clip_out - self.length)
_insert_clip(self.track, self.fade_clip, self.index + 1, 0, self.length - 1)
#-------------------- APPEND MEDIA LOG
# "track","clips"
def append_media_log_action(data):
action = EditAction(_append_media_log_undo,_append_media_log_redo, data)
return action
def _append_media_log_undo(self):
for i in range(0, len(self.clips)):
_remove_clip(self.track, len(self.track.clips) - 1)
def _append_media_log_redo(self):
for i in range(0, len(self.clips)):
clip = self.clips[i]
append_clip(self.track, clip, clip.clip_in, clip.clip_out)
# --------------------------------------------- help funcs for "range over" and "range splice out" edits
# NOTE: RANGE SPLICE OUT NOT IMPLEMENTED YET; SO THIS IS CURRENTLY DEAD CODE
def _track_put_back_range(over_in, track, track_extract_data):
# get index for first clip that was removed
moved_index = track.get_clip_index_at(over_in)
# Fix in clip and remove cut created clip if in was cut
if track_extract_data.in_clip_out != -1:
in_clip = _remove_clip(track, moved_index - 1)
if in_clip.is_blanck_clip != True:
_insert_clip(track, in_clip, moved_index - 1,
in_clip.clip_in, track_extract_data.in_clip_out)
else: # blanks can't be resized, so must put in new blank
_insert_blank(track, moved_index - 1, track_extract_data.in_clip_out - in_clip.clip_in + 1)
track_extract_data.removed_clips.pop(0)
# Fix out clip and remove cut created clip if out was cut
if track_extract_data.out_clip_in != -1:
try:
out_clip = _remove_clip(track, moved_index)
if len(track_extract_data.removed_clips) > 0: # If overwrite was done inside single clip everything is already in order
# because setting in_clip back to its original length restores original state
if out_clip.is_blanck_clip != True:
_insert_clip(track, track_extract_data.orig_out_clip, moved_index,
track_extract_data.out_clip_in, out_clip.clip_out)
else: # blanks can't be resized, so must put in new blank
_insert_blank(track, moved_index, track_extract_data.out_clip_length)
track_extract_data.removed_clips.pop(-1)
except:
# If moved clip/s were last in the track and were moved slightly
# forward and were still last in track after move
# this leaves a trailing black that has been removed and this will fail
pass
# Put back old clips
for i in range(0, len(track_extract_data.removed_clips)):
clip = track_extract_data.removed_clips[i]
_insert_clip(track, clip, moved_index + i, clip.clip_in,
clip.clip_out)
#_remove_trailing_blanks(track)
# NOTE: RANGE SPLICE OUT NOT IMPLEMENTED YET; SO THIS IS BASICALLY UNNECESSARY METHOD CAUSING
# CODE DUPLICATION WITH OTHER OVERWRITE METHODS
def _track_extract_range(over_in, over_out, track):
track_extract_data = utils.EmptyClass()
# Find out if overwrite starts after track end and pad track with blanck if so
if over_in >= track.get_length():
track_extract_data.starts_after_end = True
gap = over_out - track.get_length()
_insert_blank(track, len(track.clips), gap)
else:
track_extract_data.starts_after_end = False
# Cut at in point if not already on cut
clip_in, clip_out = _overwrite_cut_track(track, over_in)
track_extract_data.in_clip_out = clip_out
# Cut at out point if not already on cut
track_extract_data.orig_out_clip = None
if track.get_length() > over_out:
clip_in, clip_out = _overwrite_cut_track(track, over_out, True)
track_extract_data.out_clip_in = clip_in
track_extract_data.out_clip_length = clip_out - clip_in + 1 # Cut blank can't be reconstructed with clip_in data as it is always 0 for blank, so we use this
if clip_in != -1: # if we did cut we'll need to restore the dut out clip
# which is the original clip because
orig_index = track.get_clip_index_at(over_out - 1)
track_extract_data.orig_out_clip = track.clips[orig_index]
else:
track_extract_data.out_clip_in = -1
# Splice out clips in overwrite range
track_extract_data.removed_clips = []
track_extract_data.in_index = track.get_clip_index_at(over_in)
out_index = track.get_clip_index_at(over_out)
for i in range(track_extract_data.in_index, out_index):
removed_clip = _remove_clip(track, track_extract_data.in_index)
track_extract_data.removed_clips.append(removed_clip)
return track_extract_data
# ------------------------------------------------ SLOW/FAST MOTION
# "track","clip","clip_index","speed":speed}
def replace_with_speed_changed_clip(data):
action = EditAction(_replace_with_speed_changed_clip_undo, _replace_with_speed_changed_clip_redo, data)
return action
def _replace_with_speed_changed_clip_undo(self):
pass
def _replace_with_speed_changed_clip_redo(self):
# Create slowmo clip if it does not exists
if not hasattr(self, "new_clip"):
self.new_clip = current_sequence().create_slowmotion_producer(self.clip.path, self.speed)
current_sequence().clone_clip_and_filters(self.clip, self.new_clip)
_remove_clip(self.track, self.clip_index)
_insert_clip(self.track, self.new_clip, self.clip_index, self.clip.clip_in, self.clip.clip_out)
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.