コード例 #1
0
class Window(QtGui.QWidget):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.setWindowTitle(self.tr("Basic Drawing"))
        
        world_folder = 'C:\Users\Admin\AppData\Roaming\.minecraft\saves\Ostrova01'
        #world_folder = 'C:\Users\Yuretzz\AppData\Roaming\.minecraft\saves\Ostrova01'
        #world_folder = 'D:\Distrib\Ostrova01'
        
        self.wf = MyWorld(world_folder)
        print self.wf.spawnChunkCoord
        
        self.chank = self.wf.loadChunk((-12, 25))
        print self.chank.oreStatistics
        
        self.chank.createCube()
        self.sm = SelectedMinerals(self.chank)
        
        # add barzel, obsidian ve peham (zaav remains)
        self.sm.changeListOfActive([14, 15, 73, 16])    
        print 'Added barzel, obsidian ve peham (zaav remains):'
        
        print 'Now show only zaav ve barzel:'
        self.sm.changeListOfActive([14, 15])
        
        self.prj = Projector()
        self.prj.setupPrism(800)
        self.sm.minerals[9].project(self.prj)
        
        self.renderArea = RenderArea(self)

        mainLayout = QtGui.QGridLayout()
        mainLayout.addWidget(self.renderArea, 0, 0)
        self.setLayout(mainLayout)
コード例 #2
0
    def __init__(self,
                 num_classes=1,
                 dim=32,
                 num_tokens=8,
                 token_c=32,
                 mlp_dim=128,
                 heads=8,
                 depth=2,
                 dropout=0.1):
        super(ViTNet, self).__init__()

        self.conv1 = Conv3d(1,
                            16,
                            kernel_size=3,
                            stride=1,
                            bias=False,
                            padding=1)
        self.conv2 = Conv3d(16,
                            dim,
                            kernel_size=3,
                            stride=1,
                            bias=False,
                            padding=1)
        self.bn1 = BatchNorm3d(16)
        self.bn2 = BatchNorm3d(dim)
        self.pool1 = MaxPool3d(2)
        self.pool2 = MaxPool3d(2)
        self.apply(_weights_init)  # 權重初始化

        # Tokenization
        self.token_wA = Linear(dim, num_tokens)  # Tokenization parameters
        torch.nn.init.xavier_uniform_(self.token_wA.weight)
        self.mat = einsum('bij,bjk->bik')
        self.token_wV = Linear(dim, token_c)  # Tokenization parameters
        torch.nn.init.xavier_uniform_(self.token_wV.weight)

        self.transformer = Transformer(token_c, depth, heads, mlp_dim, dropout)
        self.to_cls_token = nn.Identity()
        self.projector = Projector(in_channels=dim,
                                   out_channels=16,
                                   token_channels=token_c)

        # output
        self.nn1 = Linear(16 * 16 * 16 * 16, 2048)
        self.act1 = ReLU()
        torch.nn.init.xavier_uniform_(self.nn1.weight)
        torch.nn.init.normal_(self.nn1.bias, std=1e-6)
        self.do1 = Dropout(dropout)
        self.nn2 = Linear(2048, 128)
        self.act2 = ReLU()
        torch.nn.init.xavier_uniform_(self.nn2.weight)
        torch.nn.init.normal_(self.nn2.bias, std=1e-6)
        self.nn3 = Linear(128, num_classes)
        torch.nn.init.xavier_uniform_(self.nn3.weight)
        torch.nn.init.normal_(self.nn3.bias, std=1e-6)
コード例 #3
0
def main():
    t0 = time.time()
    print('t0:', t0)

    # Initialize TensorFlow.
    tflib.init_tf()  # 0.82s

    print('t1:', time.time() - t0)

    # Load pre-trained network.
    with open('./models/stylegan2-ffhq-config-f.pkl', 'rb') as f:
        print('t2:', time.time() - t0)

        _G, _D, Gs = pickle.load(f)  # 13.09s

        print('t3:', time.time() - t0)

    with open('./models/vgg16_zhang_perceptual.pkl', 'rb') as f:
        lpips = pickle.load(f)

        print('t4:', time.time() - t0)

    proj = Projector()
    proj.set_network(Gs, lpips)

    image = PIL.Image.open('./images/example.png')
    #image = image.resize((Di.input_shape[2], Di.input_shape[3]), PIL.Image.ANTIALIAS)
    image_array = np.array(image).swapaxes(0, 2).swapaxes(1, 2)
    image_array = misc.adjust_dynamic_range(image_array, [0, 255], [-1, 1])

    print('t5:', time.time() - t0)

    proj.start([image_array])
    for step in proj.runSteps(1000):
        print('\rstep: %d' % step, end='', flush=True)
        if step % 10 == 0:
            results = proj.get_images()
            pilImage = misc.convert_to_pil_image(
                misc.create_image_grid(results), drange=[-1, 1])
            pilImage.save('./images/project-%d.png' % step)

    print('t6:', time.time() - t0)

    dlatents = proj.get_dlatents()
    noises = proj.get_noises()
    print('dlatents:', dlatents.shape)
    print('noises:', len(noises), noises[0].shape, noises[-1].shape)
コード例 #4
0
ファイル: gan.py プロジェクト: maharshi95/3d-recon
    def __init__(self, config):
        super(GAN, self).__init__()
        self.config = config
        self.e_net = Encoder(config)
        self.g_net = Decoder(config)
        self.d_net = Disc(config)
        self.p_net = Projector(config)

        self._build_optimizers()
コード例 #5
0
def loadProjector():
	global g_Projector
	if g_Projector:
		return g_Projector

	gs, _ = loadGs()
	lpips = loadLpips()

	g_Projector = Projector()
	g_Projector.regularize_noise_weight = float(os.environ.get('REGULARIZE_NOISE_WEIGHT', 1e5))
	g_Projector.initial_noise_factor = float(os.environ.get('INITIAL_NOISE_FACTOR', 0.05))
	g_Projector.uniform_latents = int(os.environ.get('UNIFORM_LATENTS', 0)) > 0
	g_Projector.euclidean_dist_weight = float(os.environ.get('EUCLIDEAN_DIST_WEIGHT', 1))
	g_Projector.regularize_magnitude_weight = float(os.environ.get('REGULARIZE_MAGNITUDE_WEIGHT', 0))
	g_Projector.set_network(gs, lpips)

	return g_Projector
コード例 #6
0
def main():
	startMessage()
	
	#servo = PWM.Servo()
	servo = "STUB"
	
	# Create objects
	projo = Projector()
	z_stepper = ZStepper()
	shutter = Shutter(servo)
	tilt = Tilt(servo)
	safety = Safety()
	safety.addActivePins(z_stepper.getUsedPins())
	safety.addActivePins(shutter.getUsedPins())
	safety.addActivePins(tilt.getUsedPins())
	
	# test projo function
	projo.switchOn()
	projo.switchOff()
	
	# test Z stepper
	z_stepper.setTargetPos(199800, 1000)
	z_stepper.run()
	
	# test shutter function
	shutter.close()
	shutter.open()
	shutter.close()
	
	#test tilt function
	tilt.tiltMe()
	
	# check output pins to desactivate for safety
	print "Safety pins watched :" + repr(safety.getActivePins())

	#listAllScenarioFiles("/home/lsa/Documents/DLP_Printer_soft_Freaky/gear.slice/")
	fenetre = Tk()
	label = Label(fenetre, text="Hello World")
	label.pack()
コード例 #7
0
ファイル: pS.py プロジェクト: Donlanes/donlanes-projector
def main():
    try:
        projector = Projector()
    except ProjectorNotConnected:
        no_projector_message()
        sys.exit(-1)

    light = Light()

    if len(sys.argv) <= 1:
        print "Command required."
        sys.exit(-1)
    command = sys.argv[1]

    time.sleep(.5)

    # Control light.
    if command == 'ON' :
        light.set_state(False)
    elif command == 'OFF' :
        light.set_state(True)
    elif command == '711':
        if not ENABLE_SEVLEV_EMAIL:
            log_to_file('711.mail.disabled\n')

        if light.sevlev() and ENABLE_SEVLEV_EMAIL:
            SEVLEV_EMAIL_INTERVAL = 5*60 # 30 minutes
            if int(time.time()) - get_last_email_sent_time() > SEVLEV_EMAIL_INTERVAL:
                log_to_file('711.mail.sending\n')
                send_sevlev_mail()
                save_last_email_sent_time()
            else:
                log_to_file('711.mail.ignoring\n')
    elif (command == '711-force'):
        send_sevlev_mail()

    # Control projector.
    if projector.is_valid_cmd(command):
        projector.run_cmd(command)
コード例 #8
0
ファイル: browser.py プロジェクト: aGutscher/qgisws
    def __init__(self, app):
        QDialog.__init__(self)
        self.setupUi(self)
        self.app = app
        # init attributes
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
        
        self.filename = "/home/vagrant/Bureau/fork/qgisws/banskel/bano-75.csv"
        
        self.browseButton.clicked.connect(self.__browse)
        self.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(self.__ok)
        self.buttonBox.button(QDialogButtonBox.Cancel).clicked.connect(app.quit)

        self.projector = Projector()
        self.progress = Progress()
コード例 #9
0
def main():
    amp = Amplifier("Top-O-Line-Amplifier")
    tuner = Tuner("Top-O-Line AM/FM Tuner", amp)
    dvd_player = DvdPlayer("Top-O-Line DVD Player", amp)
    cd_player = CDPlayer("Top-O-Line CD Player", amp)
    projector = Projector("Top-O-Line Projector", dvd_player)
    lights = TheaterLights("Theater Ceiling Lights")
    screen = Screen("Theater Screen")
    popper = PopcornPopper("Popcorn Popper")

    home_theater = HomeTheaterFacade(amp, tuner, dvd_player, cd_player,
                                     projector, screen, lights, popper)
    home_theater.watch_movie("Lord of the Rings")
    print()
    home_theater.end_movie()
    print()
コード例 #10
0
 def _createServices(self, eventloop):
     """Hardcoding a list of services - later we might add auto-detection of services present"""
     Airconditioner(self, self.config, eventloop)
     AutoShade(self, self.config, eventloop)
     AutoLight(self, self.config, eventloop)
     HiFi(self, self.config, eventloop)
     IrTrans(self, self.config, eventloop)
     Kodi(self, self.config, eventloop)
     Paradox(self, self.config, eventloop)
     Projector(self, self.config, eventloop)
     Scene(self, self.config, eventloop)
     Schedule(self, self.config, eventloop)
     SleepSense(self, self.config, eventloop)
     SunRiseSet(self, self.config, eventloop)
     ZWaveMios(self, self.config, eventloop)
     # let's make this last:
     TcpServer(self, self.config, eventloop)
コード例 #11
0
ファイル: browser.py プロジェクト: lao-tseu-is-alive/qgisws
    def __init__(self):
        QDialog.__init__(self)
        self.setupUi(self)
        self._filename = ""
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
        self.progressBar.setVisible(False)
        self._my_projector = Projector()
        self._my_projector.signal_in_progress.connect(self.__in_progress)
        # init attributes
        # TODO

        # custom settings for widgets
        # TODO

        # connect
        # TODO
        #QObject.connect(self, self.pushButtonBrowse, SIGNAL('clicked()'), __browse)
        self.pushButtonBrowse.clicked.connect(self.__browse)
コード例 #12
0
from projector import Projector

world_folder = 'C:\Users\Admin\AppData\Roaming\.minecraft\saves\Ostrova01'
#world_folder = 'C:\Users\Yuretzz\AppData\Roaming\.minecraft\saves\Ostrova01'
#world_folder = 'D:\Distrib\Ostrova01'

wf = MyWorld(world_folder)
print wf.spawnChunkCoord

chank = Chunk(wf, (-12, 25))
print chank.oreStatistics

chank.createCube()
sm = SelectedMinerals(chank)

# add barzel, obsidian ve peham (zaav remains)
sm.changeListOfActive([14, 15, 73, 16])    
print 'Added barzel, obsidian ve peham (zaav remains):'

print 'Now show only zaav ve barzel:'
sm.changeListOfActive([14, 15])

prj = Projector()
prj.setupPrism(800)
sm.minerals[14].project(prj)

#print 'Now completely change:'
#sm.changeListOfActive([73, 56])

puk=1
コード例 #13
0
ファイル: main.py プロジェクト: wobakj/avango
def start():
    # setup scenegraph
    graph = avango.gua.nodes.SceneGraph(Name="scenegraph")
    loader = avango.gua.nodes.TriMeshLoader()

    projector = Projector()
    projector.Graph.value = graph
    projector.Texture.value = "data/textures/smiley.jpg"

    monkey = loader.create_geometry_from_file(
        "monkey", "data/objects/monkey.obj",
        avango.gua.LoaderFlags.NORMALIZE_SCALE)
    monkey.Material.connect_from(projector.Material)

    light = avango.gua.nodes.LightNode(
        Type=avango.gua.LightType.POINT,
        Name="light",
        Color=avango.gua.Color(1.0, 1.0, 1.0),
        Brightness=50.0,
        Transform=avango.gua.make_trans_mat(1, 1, 5) *
        avango.gua.make_scale_mat(15, 15, 15))

    size = avango.gua.Vec2ui(1024, 768)

    window = avango.gua.nodes.GlfwWindow(Size=size, LeftResolution=size)

    avango.gua.register_window("window", window)

    cam = avango.gua.nodes.CameraNode(LeftScreenPath="/screen",
                                      SceneGraph="scenegraph",
                                      Resolution=size,
                                      OutputWindowName="window",
                                      Transform=avango.gua.make_trans_mat(
                                          0.0, 0.0, 3.5))

    pipeline_description = avango.gua.nodes.PipelineDescription(Passes=[
        avango.gua.nodes.TriMeshPassDescription(),
        avango.gua.nodes.LightVisibilityPassDescription(),
        avango.gua.nodes.ResolvePassDescription()
    ])

    cam.PipelineDescription.value = pipeline_description

    screen = avango.gua.nodes.ScreenNode(Name="screen",
                                         Width=2,
                                         Height=1.5,
                                         Children=[cam])

    graph.Root.value.Children.value = [
        monkey, light, screen, projector.group_node
    ]

    #setup viewer
    viewer = avango.gua.nodes.Viewer()
    viewer.SceneGraphs.value = [graph]
    viewer.Windows.value = [window]

    #monkey rotation
    monkey_updater = TimedRotate()
    timer = avango.nodes.TimeSensor()
    monkey_updater.TimeIn.connect_from(timer.Time)
    monkey.Transform.connect_from(monkey_updater.MatrixOut)

    # projector movement
    navigator = Navigator()
    navigator.OutTransform.value = avango.gua.make_identity_mat()
    navigator.StartLocation.value = avango.gua.Vec3(0.0, 0.0, 1.0)

    navigator.RotationSpeed.value = 0.2
    navigator.MotionSpeed.value = 0.04

    projector.Transform.connect_from(navigator.OutTransform)

    guaVE = GuaVE()
    guaVE.start(locals(), globals())

    viewer.run()
コード例 #14
0
ファイル: cube.py プロジェクト: mirmik/sopr-scheme-gener
    def drawCube(self, i, off=0):
        def deg(x):
            return x / 180.0 * math.pi

        proj = Projector()
        proj.set_yaw(deg(self.shemetype.zrot.get()))
        proj.set_pitch(-deg(self.shemetype.xrot.get()))
        proj.set_zmul(self.shemetype.zmul.get())
        proj.set_iso_projection(not self.shemetype.axonom.get())

        if i == 1:
            proj.set_mov(off, 0)

        P = self.shemetype.rebro.get()
        red = QPen()
        green = QPen()
        blue = QPen()

        red.setColor(QColor(255, 0, 0))
        green.setColor(QColor(0, 255, 0))
        blue.setColor(QColor(0, 0, 255))

        self.scene.addLine(QLineF(proj(+P, +P, +P), proj(-P, +P, +P)),
                           self.pen)
        self.scene.addLine(QLineF(proj(+P, +P, +P), proj(+P, -P, +P)),
                           self.pen)
        self.scene.addLine(QLineF(proj(+P, +P, +P), proj(+P, +P, -P)),
                           self.pen)
        self.scene.addLine(QLineF(proj(+P, +P, -P), proj(-P, +P, -P)),
                           self.pen)
        self.scene.addLine(QLineF(proj(+P, +P, -P), proj(+P, -P, -P)),
                           self.pen)
        self.scene.addLine(QLineF(proj(-P, +P, -P), proj(-P, +P, +P)),
                           self.pen)
        self.scene.addLine(QLineF(proj(+P, -P, -P), proj(+P, -P, +P)),
                           self.pen)
        self.scene.addLine(QLineF(proj(-P, -P, +P), proj(-P, +P, +P)),
                           self.pen)
        self.scene.addLine(QLineF(proj(-P, -P, +P), proj(+P, -P, +P)),
                           self.pen)

        #axes:
        self.scene.addItem(
            ArrowItem(proj(+P, -P, -P),
                      proj(+2 * P, -P, -P),
                      arrow_size=(15, 3),
                      pen=self.halfpen,
                      brush=Qt.black))
        self.scene.addItem(
            ArrowItem(proj(-P, +P, -P),
                      proj(-P, +2 * P, -P),
                      arrow_size=(15, 3),
                      pen=self.halfpen,
                      brush=Qt.black))
        self.scene.addItem(
            ArrowItem(proj(-P, -P, +P),
                      proj(-P, -P, +2 * P),
                      arrow_size=(15, 3),
                      pen=self.halfpen,
                      brush=Qt.black))
        self.scene.addItem(
            TextItem("x",
                     font=self.font,
                     center=proj(+2 * P, -P, -P) + QPointF(0, -10),
                     pen=self.pen))
        self.scene.addItem(
            TextItem("z",
                     font=self.font,
                     center=proj(-P, +2 * P, -P) + QPointF(-8, 0),
                     pen=self.pen))
        self.scene.addItem(
            TextItem("y",
                     font=self.font,
                     center=proj(-P, -P, +2 * P) + QPointF(-8, 0),
                     pen=self.pen))

        #forces:
        qx = self.shemetype.task["sections"][i].qx
        qy = self.shemetype.task["sections"][i].qy
        qz = self.shemetype.task["sections"][i].qz
        mx = self.shemetype.task["sections"][i].mx
        my = self.shemetype.task["sections"][i].my
        mz = self.shemetype.task["sections"][i].mz

        qx_pnt = proj(2.5 * P, 0, 0)
        qy_pnt = proj(0, 0, 2.5 * P)
        qz_pnt = proj(0, 2.5 * P, 0)

        if qx != "нет":
            self.scene.addItem(
                ArrowItem(proj(P, 0, 0),
                          qx_pnt,
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=qx == "-"))
        if qy != "нет":
            self.scene.addItem(
                ArrowItem(proj(0, 0, P),
                          qy_pnt,
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=qy == "-"))
        if qz != "нет":
            self.scene.addItem(
                ArrowItem(proj(0, P, 0),
                          qz_pnt,
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=qz == "-"))

        M = 3 / 4
        if mz != "нет":
            reverse = mz == "-"
            self.scene.addItem(
                ArrowItem(proj(-P * M, 0, P),
                          proj(P * M, 0, P),
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=reverse))
            self.scene.addItem(
                ArrowItem(proj(P, 0, -P * M),
                          proj(P, 0, P * M),
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=reverse))

        if my != "нет":
            reverse = my == "-"
            self.scene.addItem(
                ArrowItem(proj(-P * M, P, 0),
                          proj(P * M, P, 0),
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=reverse))
            self.scene.addItem(
                ArrowItem(proj(P, -P * M, 0),
                          proj(P, P * M, 0),
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=reverse))

        if mx != "нет":
            reverse = mx == "-"
            self.scene.addItem(
                ArrowItem(proj(0, -P * M, P),
                          proj(0, P * M, P),
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=reverse))
            self.scene.addItem(
                ArrowItem(proj(0, P, -P * M),
                          proj(0, P, P * M),
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=reverse))

        #labels:
        if i == 0:

            def do_label(i, pnt=QPointF(0, 0), hint=None):
                text = self.shemetype.task["labels"][i].text
                x = self.shemetype.task["labels"][i].x
                y = self.shemetype.task["labels"][i].y
                item = TextItem(paintool.greek(text),
                                font=self.font,
                                center=pnt + QPointF(x, y),
                                pen=self.pen)
                self.scene.addItem(item)
                self.hovers[hint] = item
                item.hint = hint

            section = self.shemetype.task["sections"][0]
            if section.qx != "нет": do_label(0, qx_pnt, hint="qx")
            if section.qy != "нет": do_label(1, qy_pnt, hint="qy")
            if section.qz != "нет": do_label(2, qz_pnt, hint="qz")
            if section.mx != "нет": do_label(3, proj(0, 0, P), hint="mx")
            if section.my != "нет": do_label(4, proj(0, P, 0), hint="my")
            if section.mz != "нет": do_label(5, proj(P, 0, 0), hint="mz")

        if i == 1:

            def do_label(i, pnt=QPointF(0, 0), hint=None):
                text = self.shemetype.task["labels"][i].text2
                x = self.shemetype.task["labels"][i].x2
                y = self.shemetype.task["labels"][i].y2
                item = TextItem(text,
                                font=self.font,
                                center=pnt + QPointF(x, y),
                                pen=self.pen)
                self.scene.addItem(item)
                self.hovers[hint] = item
                item.hint = hint

            section = self.shemetype.task["sections"][1]
            if section.qx != "нет": do_label(0, qx_pnt, hint="qx2")
            if section.qy != "нет": do_label(1, qy_pnt, hint="qy2")
            if section.qz != "нет": do_label(2, qz_pnt, hint="qz2")
            if section.mx != "нет": do_label(3, proj(0, 0, P), hint="mx2")
            if section.my != "нет": do_label(4, proj(0, P, 0), hint="my2")
            if section.mz != "нет": do_label(5, proj(P, 0, 0), hint="mz2")
コード例 #15
0
ファイル: test_projector.py プロジェクト: louieliu97/VABS
##################################################################################
# Title: camera.py
# Author: Louie Liu
# Date: 15 April 2020
##################################################################################


from projector import Projector
import cv2

import numpy as np

p = Projector()
color = p.camera.getColorImage()
img = p.blankScreen()

cv2.namedWindow("window",cv2.WND_PROP_FULLSCREEN)
cv2.setWindowProperty("window", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
while(1):
    cv2.imshow("window", img)
    k = cv2.waitKey(33)
    if k == 27:
        break
    if k & 0b11111111 == ord('q'):
        sphero = p.findSphero()
        img = p.projectSpheroLine(sphero)
    elif k & 0b11111111 == ord('z'):
        img = p.blankScreen()
    elif k & 0b11111111 == ord('a'):
        angle = int(input("Input new angle between 0 and 360: "))
        img = p.projectSpheroLine(sphero,angle, True)
コード例 #16
0
ファイル: browser.py プロジェクト: aGutscher/qgisws
class Browser(QDialog, Ui_BrowseDialog):

    # -------------------------------------------------------------------------
    # public methods
    # -------------------------------------------------------------------------
    # -------------------------------------------------------------------------
    def __init__(self, app):
        QDialog.__init__(self)
        self.setupUi(self)
        self.app = app
        # init attributes
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
        
        self.filename = "/home/vagrant/Bureau/fork/qgisws/banskel/bano-75.csv"
        
        self.browseButton.clicked.connect(self.__browse)
        self.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(self.__ok)
        self.buttonBox.button(QDialogButtonBox.Cancel).clicked.connect(app.quit)

        self.projector = Projector()
        self.progress = Progress()

    # -------------------------------------------------------------------------
    @property
    def filename(self):
        return self.__filename

    # -------------------------------------------------------------------------
    @filename.setter
    def filename(self, filename):
        if os.path.isfile(filename):
            self.__filename = filename
            self.urlEdit.setText(self.__filename)
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
        else:
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False) 
            msg = QMessageBox()
            msg.setText("Fichier introuvable")

    # -------------------------------------------------------------------------
    # private methods
    # -------------------------------------------------------------------------
    # -------------------------------------------------------------------------
    def __in_progress(self):
        self.progress.progressBar.setValue(self.progress.progressBar.value()+1)

    # -------------------------------------------------------------------------
    def __compute_done(self):
        self.progress.close()

    # -------------------------------------------------------------------------
    def __ok(self):
        self.projector.filename = self.__filename
        
        self.projector.progressSignal.connect(self.__in_progress)
        self.projector.finishSignal.connect(self.__compute_done)
        self.projector.start()
        
        self.progress.progressBar.setRange(0,count_lines(self.__filename))
        self.progress.progressBar.setValue(0)
        self.progress.show()


    # -------------------------------------------------------------------------
    def __browse(self):
        self.filename = QFileDialog.getOpenFileName(self,"Sélectionner le fichier")
コード例 #17
0
    path = sys.argv[1]
    if os.path.isdir(path):
        image_files = glob.glob(path + '*.png')
        image_files += glob.glob(path + '*.jpg')
    else:
        image_files = [path]

    target_dir = sys.argv[2]
    os.makedirs(target_dir, exist_ok=True)

    # Load model
    g = Generator(1024, 512, 8, pretrained=True).to(device).train()
    for param in g.parameters():
        param.requires_grad = False

    proj = Projector(g)

    for i, file in tqdm(enumerate(sorted(image_files))):
        print('Projecting {}'.format(file))

        # Load image
        target_image = Image.open(file)
        transform = transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
        ])
        target_image = transform(target_image).to(device)

        # Run projector
        proj.run(target_image)
コード例 #18
0
ファイル: browser.py プロジェクト: lao-tseu-is-alive/qgisws
class Browser(QDialog, Ui_file_browser):

    # -------------------------------------------------------------------------
    # public methods
    # -------------------------------------------------------------------------
    # -------------------------------------------------------------------------
    def __init__(self):
        QDialog.__init__(self)
        self.setupUi(self)
        self._filename = ""
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
        self.progressBar.setVisible(False)
        self._my_projector = Projector()
        self._my_projector.signal_in_progress.connect(self.__in_progress)
        # init attributes
        # TODO

        # custom settings for widgets
        # TODO

        # connect
        # TODO
        #QObject.connect(self, self.pushButtonBrowse, SIGNAL('clicked()'), __browse)
        self.pushButtonBrowse.clicked.connect(self.__browse)
        #QtCore.QObject.connect(self.processThread, QtCore.SIGNAL("progress(int)"),self.progressBar, QtCore.SLOT("setValue(int)"), QtCore.Qt.QueuedConnection)


    # -------------------------------------------------------------------------
    @property
    def filename(self):
        return self._filename


    # -------------------------------------------------------------------------
    @filename.setter
    def filename(self, filename):
        if os.path.isfile(filename):
            self._filename = filename
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
            self.progressBar.setVisible(True)
            num_lines = count_lines(filename)
            self.progressBar.setMaximum(num_lines)
            self._my_projector.filename = filename
            self._my_projector.start()

        else:
            print("Selected file : {file} is not a file".format(file=filename))



    # -------------------------------------------------------------------------
    # private methods
    # -------------------------------------------------------------------------
    # -------------------------------------------------------------------------
    def __in_progress(self, line):
        self.progressBar.setValue(line)
        print(line)

    # -------------------------------------------------------------------------
    def __compute_done(self):
        # TODO
        pass

    # -------------------------------------------------------------------------
    def __ok(self):
        # TODO
        pass

    # -------------------------------------------------------------------------
    def __browse(self):
        # TODO
        #myFileDialog = QFileDialog(self)
        #myFileDialog.show()
        self.filename = QFileDialog.getOpenFileName(self, 'Choose File', '.',  '*.csv',)
        print(self.filename)
        self.lineEditFileName.setText(self.filename)
コード例 #19
0
ファイル: master_controles.py プロジェクト: linksf/pixeland
    (Projector) stores the pattens from the controller, feeds a pattern to the Grid, taking a generator object of
     frames in return. It then creates a clock and puts the frame to the physcial pixels at the appropriate fps. When
     a generator is out of instances the projector sends the next pattern to the grid and starts the process again.

Bit Cycle (specific steps between loading the current pattern and putting pixels):
    a. (Projector) frame = calls self._grid.pixelate(pattern, fps, duration)
    b. (Grid) runs a setup for pattern which creates 1 or more Bit objects and any limbs it/they have
    c. (Grid) uses the loop part of the pattern to call methods on all or some of the bits, causing them to change one or
        more attributes such as size, position, color, etc. and yields the result to (Projector) under the variable 'frame'
        ** the generator object will produce at least (fps * duration) frames**
    d. (Projector) uses the pyGame clock ticker to put_pixles (next(frame)) to the client a fps frames per second
'''

# internal imports
from grid import Grid
from bits import Bit
from paterns import *
from projector import Projector

#external imports

# create 'global' variables
fps = 60
dimensions = (16,16)
# CREATE GRID
grid = Grid(dimensions=dimensions)
# CREATE PROJECTOR
projector = Projector(fps=fps, grid=grid)
# send patterns to grid and initialize

コード例 #20
0
ファイル: builder.py プロジェクト: gohome/titanium_mobile
def main(args):
	global script_ok
	argc = len(args)
	if argc < 2 or argc==2 and (args[1]=='--help' or args[1]=='-h'):
		print "%s <command> <version> <project_dir> <appid> <name> [options]" % os.path.basename(args[0])
		print
		print "available commands: "
		print
		print "  install       install the app to itunes for testing on iphone"
		print "  simulator     build and run on the iphone simulator"
		print "  distribute    build final distribution bundle"
		print "  xcode         build from within xcode"
		print "  run           build and run app from project folder"
	
		sys.exit(1)

	print "[INFO] One moment, building ..."
	sys.stdout.flush()
	start_time = time.time()
	command = args[1].decode("utf-8")
	
	target = 'Debug'
	deploytype = 'development'
	devicefamily = 'iphone'
	debug = False
	simulator = False
	xcode_build = False
	force_xcode = False
	
	if command == 'xcode':
		xcode_build = True
		src_root = os.environ['SOURCE_ROOT']
		project_dir = os.path.abspath(os.path.join(src_root,'../','../'))
		name = os.environ['PROJECT_NAME']
		target = os.environ['CONFIGURATION']
		appid = os.environ['TI_APPID']
		arch = os.environ['CURRENT_ARCH']
		sdk_name = os.environ['SDK_NAME']
		iphone_version = sdk_name.replace('iphoneos','').replace('iphonesimulator','')
		# SUPPORTED_DEVICE_FAMILIES 1 or 2 or both
		# TARGETED_DEVICE_FAMILY 1 or 2
		target_device = os.environ['TARGETED_DEVICE_FAMILY']
		if target_device == '1':
			devicefamily = 'iphone'
		elif target_device == '2':
			devicefamily = 'ipad'
		if arch == 'i386': 
			# simulator always indicates simulator
			deploytype = 'development'
		else:
			# if arch!=i386 indicates a build for device
			if target=='Debug':
				# non-simulator + debug build indicates test on device
				deploytype = 'test'
			else:
				# non-simulator + release build indicates package for distribution
				deploytype = 'production'
		compiler = Compiler(project_dir,appid,name,deploytype,xcode_build,devicefamily,iphone_version)
		script_ok = True
		sys.exit(0)
	else:
		if command == 'run':
			if argc < 3:
				print "Usage: %s run <project_dir> [ios_version]" % os.path.basename(args[0])
				sys.exit(1)
			if argc == 3:
				iphone_version = check_iphone_sdk('4.0')
			else:
				iphone_version = dequote(args[3].decode("utf-8"))
			project_dir = os.path.expanduser(dequote(args[2].decode("utf-8")))
			iphonesim = os.path.abspath(os.path.join(template_dir,'iphonesim'))
			iphone_dir = os.path.abspath(os.path.join(project_dir,'build','iphone'))
			tiapp_xml = os.path.join(project_dir,'tiapp.xml')
			ti = TiAppXML(tiapp_xml)
			appid = ti.properties['id']
			name = ti.properties['name']
			command = 'simulator' # switch it so that the rest of the stuff works
		else:
			iphone_version = dequote(args[2].decode("utf-8"))
			iphonesim = os.path.abspath(os.path.join(template_dir,'iphonesim'))
			project_dir = os.path.expanduser(dequote(args[3].decode("utf-8")))
			appid = dequote(args[4].decode("utf-8"))
			name = dequote(args[5].decode("utf-8"))
			tiapp_xml = os.path.join(project_dir,'tiapp.xml')
			ti = TiAppXML(tiapp_xml)
			
		app_name = make_app_name(name)
		iphone_dir = os.path.abspath(os.path.join(project_dir,'build','iphone'))
		project_xcconfig = os.path.join(iphone_dir,'project.xcconfig')
		target = 'Release'
		ostype = 'os'
		version_file = None
		log_id = None
		provisioning_profile = None
		
		# starting in 1.4, you don't need to actually keep the build/iphone directory
		# if we don't find it, we'll just simply re-generate it
		if not os.path.exists(iphone_dir):
			from iphone import IPhone
			print "[INFO] Detected missing project but that's OK. re-creating it..."
			iphone_creator = IPhone(name,appid)
			iphone_creator.create(iphone_dir,True)
			sys.stdout.flush()
			
		
		if command == 'distribute':
			iphone_version = check_iphone_sdk(iphone_version)
			appuuid = dequote(args[6].decode("utf-8"))
			dist_name = dequote(args[7].decode("utf-8"))
			output_dir = os.path.expanduser(dequote(args[8].decode("utf-8")))
			if argc > 9:
				devicefamily = dequote(args[9].decode("utf-8"))
			deploytype = 'production'
		elif command == 'simulator':
			deploytype = 'development'
			debug = True
			simulator = True
			target = 'Debug'
			ostype = 'simulator'
			if argc > 6:
				devicefamily = dequote(args[6].decode("utf-8"))
		elif command == 'install':
			iphone_version = check_iphone_sdk(iphone_version)
			appuuid = dequote(args[6].decode("utf-8"))
			dist_name = dequote(args[7].decode("utf-8"))
			if argc > 8:
				devicefamily = dequote(args[8].decode("utf-8"))
			deploytype = 'test'
		
		build_out_dir = os.path.abspath(os.path.join(iphone_dir,'build'))
		build_dir = os.path.abspath(os.path.join(build_out_dir,'%s-iphone%s'%(target,ostype)))
		app_dir = os.path.abspath(os.path.join(build_dir,name+'.app'))
		binary = os.path.join(app_dir,name)
		sdk_version = os.path.basename(os.path.abspath(os.path.join(template_dir,'../')))
		iphone_resources_dir = os.path.join(iphone_dir,'Resources')
		version_file = os.path.join(iphone_resources_dir,'.version')
		force_rebuild = read_project_version(project_xcconfig)!=sdk_version or not os.path.exists(version_file)
		infoplist = os.path.join(iphone_dir,'Info.plist')
		githash = None
		custom_fonts = []

		if command!='simulator' and os.path.exists(build_out_dir):
			shutil.rmtree(build_out_dir)
		if not os.path.exists(build_out_dir): 
			os.makedirs(build_out_dir)
		# write out the build log, useful for debugging
		o = codecs.open(os.path.join(build_out_dir,'build.log'),'w',encoding='utf-8')
		try:
			buildtime = datetime.datetime.now()
			o.write("%s\n" % ("="*80))
			o.write("Appcelerator Titanium Diagnostics Build Log\n")
			o.write("The contents of this file are useful to send to Appcelerator Support if\n")
			o.write("reporting an issue to help us understand your environment, build settings\n")
			o.write("and aid in debugging. Please attach this log to any issue that you report.\n")
			o.write("%s\n\n" % ("="*80))
			o.write("Starting build at %s\n\n" % buildtime.strftime("%m/%d/%y %H:%M"))
			
			# write out the build versions info
			versions_txt = read_config(os.path.join(template_dir,'..','version.txt'))
			o.write("Build details:\n\n")
			for key in versions_txt:
				o.write("   %s=%s\n" % (key,versions_txt[key]))
			o.write("\n\n")
			
			if versions_txt.has_key('githash'): 
				githash = versions_txt['githash']
				
			o.write("Script arguments:\n")
			for arg in args:
				o.write(unicode("   %s\n" % arg, 'utf-8'))
			o.write("\n")
			o.write("Building from: %s\n" % template_dir)
			o.write("Platform: %s\n\n" % platform.version())

			# print out path to debug
			xcode_path=run.run(["/usr/bin/xcode-select","-print-path"],True,False)
			if xcode_path:
				o.write("Xcode path is: %s\n" % xcode_path)
			else:
				o.write("Xcode path undetermined\n")

			# find the module directory relative to the root of the SDK	
			titanium_dir = os.path.abspath(os.path.join(template_dir,'..','..','..','..'))
			tp_module_dir = os.path.abspath(os.path.join(titanium_dir,'modules','iphone'))
			tp_modules = []
			tp_depends = []
			
			force_destroy_build = command!='simulator'

			def find_depends(config,depends):
				for line in open(config).readlines():
					if line.find(':')!=-1:
						(token,value)=line.split(':')
						for entry in value.join(','):
							entry = entry.strip()
							try:
								depends.index(entry)
							except:
								depends.append(entry)

			# check to see if we have any uninstalled modules
			# if we detect any zips, unzip them
			if ti.properties.has_key('modules'):
				cwd = os.getcwd()
				os.chdir(titanium_dir)
				for entry in glob.glob('%s/*.zip' % titanium_dir):
					filename = os.path.basename(entry)
					if filename.startswith('mobilesdk-'): continue
					
					print "[INFO] installing module: %s" % entry
					run.run(['/usr/bin/unzip','-o',entry])
					os.remove(entry)
				os.chdir(cwd)

			tp_lib_search_path = []
			tp_module_asset_dirs = []
			
			for module in ti.properties['modules']:
				tp_name = module['name'].lower()
				tp_version = module['version']
				libname = 'lib%s.a' % tp_name
				# check first in the local project
				local_tp = os.path.join(project_dir,'modules','iphone',libname)
				local = False
				tp_dir = None
				if os.path.exists(local_tp):
					tp_modules.append(local_tp)
					tp_lib_search_path.append([libname,local_tp])
					local = True
					print "[INFO] Detected third-party module: %s" % (local_tp)
					o.write("Detected third-party module: %s\n" % (local_tp))
				else:
					tp_dir = os.path.join(tp_module_dir,tp_name,tp_version)
					if not os.path.exists(tp_dir):
						print "[ERROR] Third-party module: %s/%s detected in tiapp.xml but not found at %s" % (tp_name,tp_version,tp_dir)
						o.write("[ERROR] Third-party module: %s/%s detected in tiapp.xml but not found at %s\n" % (tp_name,tp_version,tp_dir))
						sys.exit(1)
					tp_module = os.path.join(tp_dir,libname)
					if not os.path.exists(tp_module):
						print "[ERROR] Third-party module: %s/%s missing library at %s" % (tp_name,tp_version,tp_module)
						o.write("[ERROR] Third-party module: %s/%s missing library at %s\n" % (tp_name,tp_version,tp_module))
						sys.exit(1)
					tp_config = os.path.join(tp_dir,'manifest')
					if not os.path.exists(tp_config):
						print "[ERROR] Third-party module: %s/%s missing manifest at %s" % (tp_name,tp_version,tp_config)
						o.write("[ERROR] Third-party module: %s/%s missing manifest at %s\n" % (tp_name,tp_version,tp_config))
						sys.exit(1)
					find_depends(tp_config,tp_depends)	
					tp_modules.append(tp_module)
					tp_lib_search_path.append([libname,os.path.abspath(tp_module)])	
					print "[INFO] Detected third-party module: %s/%s" % (tp_name,tp_version)
					o.write("Detected third-party module: %s/%s\n" % (tp_name,tp_version))
				force_xcode = True

				if not local:
					# copy module resources
					img_dir = os.path.join(tp_dir,'assets','images')
					if os.path.exists(img_dir):
						dest_img_dir = os.path.join(app_dir,'modules',tp_name,'images')
						if not os.path.exists(dest_img_dir):
							os.makedirs(dest_img_dir)
						tp_module_asset_dirs.append([img_dir,dest_img_dir])

					# copy in any module assets
					tp_assets_dir = os.path.join(tp_dir,'assets')
					if os.path.exists(tp_assets_dir): 
						module_dir = os.path.join(app_dir,'modules',tp_name)
						tp_module_asset_dirs.append([tp_assets_dir,module_dir])


			print "[INFO] Titanium SDK version: %s" % sdk_version
			print "[INFO] iPhone Device family: %s" % devicefamily
			print "[INFO] iPhone SDK version: %s" % iphone_version
			
			if simulator:
				# during simulator we need to copy in standard built-in module files
				# since we might not run the compiler on subsequent launches
				for module_name in ('facebook','ui'):
					img_dir = os.path.join(template_dir,'modules',module_name,'images')
					dest_img_dir = os.path.join(app_dir,'modules',module_name,'images')
					if not os.path.exists(dest_img_dir):
						os.makedirs(dest_img_dir)
					tp_module_asset_dirs.append([img_dir,dest_img_dir])

				# when in simulator since we point to the resources directory, we need
				# to explicitly copy over any files
				ird = os.path.join(project_dir,'Resources','iphone')
				if os.path.exists(ird): 
					tp_module_asset_dirs.append([ird,app_dir])
				
				for ext in ('ttf','otf'):
					for f in glob.glob('%s/*.%s' % (os.path.join(project_dir,'Resources'),ext)):
						custom_fonts.append(f)
					

			if not simulator:
				version = ti.properties['version']
				# we want to make sure in debug mode the version always changes
				version = "%s.%d" % (version,time.time())
				ti.properties['version']=version
				pp = os.path.expanduser("~/Library/MobileDevice/Provisioning Profiles/%s.mobileprovision" % appuuid)
				provisioning_profile = read_provisioning_profile(pp,o)
					
# TODO:				
# This code is used elsewhere, as well.  We should move stuff like this to
# a common file.
			def write_info_plist(infoplist_tmpl):
				plist = codecs.open(infoplist_tmpl, encoding='utf-8').read()
				plist = plist.replace('__PROJECT_NAME__',name)
				plist = plist.replace('__PROJECT_ID__',appid)
				plist = plist.replace('__URL__',appid)
				urlscheme = name.replace('.','_').replace(' ','').lower()
				plist = plist.replace('__URLSCHEME__',urlscheme)
				pf = codecs.open(infoplist,'w', encoding='utf-8')
				pf.write(plist)
				pf.close()			

			# if the user has a Info.plist in their project directory, consider
			# that a custom override
			infoplist_tmpl = os.path.join(project_dir,'Info.plist')
			if os.path.exists(infoplist_tmpl):
				shutil.copy(infoplist_tmpl,infoplist)
			else:
				infoplist_tmpl = os.path.join(template_dir,'Info.plist')
				write_info_plist(infoplist_tmpl)

			applogo = None
			clean_build = False

			# check to see if the appid is different (or not specified) - we need to re-generate
			if read_project_appid(project_xcconfig)!=appid or not infoplist_has_appid(infoplist,appid):
				clean_build = True
				force_xcode = True


			new_lib_hash = None
			lib_hash = None	
			existing_git_hash = None

			if os.path.exists(app_dir):
				if os.path.exists(version_file):
					line = open(version_file).read().strip()
					lines = line.split(",")
					v = lines[0]
					log_id = lines[1]
					if len(lines) > 2:
						lib_hash = lines[2]
						existing_git_hash = lines[3]
					if lib_hash==None:
						force_rebuild = True
					else:
						if template_dir==v and force_rebuild==False:
							force_rebuild = False
						else:
							log_id = None
				else:
					force_rebuild = True

			else:
				force_rebuild = True

			o.write("\ngithash=%s, existing_git_hash=%s\n" %(githash,existing_git_hash))
				
			if githash!=existing_git_hash:
				force_rebuild = True

			source_lib=os.path.join(template_dir,'libTiCore.a')
			fd = open(source_lib,'rb')
			m = hashlib.md5()
			m.update(fd.read(1024)) # just read 1K, it's binary
			new_lib_hash = m.hexdigest()
			fd.close()
			
			if new_lib_hash!=lib_hash:
				force_rebuild=True
				o.write("forcing rebuild since libhash (%s) not matching (%s)\n" % (lib_hash,new_lib_hash))

			lib_hash=new_lib_hash

			if force_rebuild:
				o.write("Performing full rebuild\n")
				print "[INFO] Performing full rebuild. This will take a little bit. Hold tight..."
				sys.stdout.flush()
				project = Projector(name,sdk_version,template_dir,project_dir,appid)
				project.create(template_dir,iphone_dir)	
				force_xcode = True
				if os.path.exists(app_dir): shutil.rmtree(app_dir)
				# we have to re-copy if we have a custom version
				write_info_plist(infoplist_tmpl)
				# since compiler will generate the module dependencies, we need to 
				# attempt to compile to get it correct for the first time.
				compiler = Compiler(project_dir,appid,name,deploytype,xcode_build,devicefamily,iphone_version,True)
			else:
				contents="TI_VERSION=%s\n"% sdk_version
				contents+="TI_SDK_DIR=%s\n" % template_dir.replace(sdk_version,'$(TI_VERSION)')
				contents+="TI_APPID=%s\n" % appid
				contents+="OTHER_LDFLAGS[sdk=iphoneos4*]=$(inherited) -weak_framework iAd\n"
				contents+="OTHER_LDFLAGS[sdk=iphonesimulator4*]=$(inherited) -weak_framework iAd\n"
				contents+="#include \"module\"\n"
				xcconfig = open(project_xcconfig,'w+')
				xccontents = xcconfig.read()
				if contents!=xccontents:
					o.write("writing contents of %s:\n\n%s\n" % (project_xcconfig,contents))
					o.write("old contents\n\n%s\n" % (xccontents))
					xcconfig.write(contents)
					xcconfig.close()
				else:
					o.write("Skipping writing contents of xcconfig %s\n" % project_xcconfig)

			# write out any modules into the xcode project
			# this must be done after project create above or this will be overriden
			if len(tp_lib_search_path)>0:
				proj = PBXProj()
				xcode_proj = os.path.join(iphone_dir,'%s.xcodeproj'%name,'project.pbxproj')
				current_xcode = open(xcode_proj).read()
				for tp in tp_lib_search_path:
					proj.add_static_library(tp[0],tp[1])
				out = proj.parse(xcode_proj)
				# since xcode changes can be destructive, only write as necessary (if changed)
				if current_xcode!=out:
					xo = open(xcode_proj,'w')
					xo.write(out)
					xo.close()

			cwd = os.getcwd()

			# check to see if the symlink exists and that it points to the
			# right version of the library
			libticore = os.path.join(template_dir,'libTiCore.a')
			make_link = True
			symlink = os.path.join(iphone_dir,'lib','libTiCore.a')
			if os.path.islink(symlink):
				path = os.path.realpath(symlink)
				if path.find(sdk_version) > 0:
					make_link = False
			if make_link:
				libdir = os.path.join(iphone_dir,'lib')
				if not os.path.exists(libdir): os.makedirs(libdir)
				os.chdir(libdir)
				# a broken link will not return true on os.path.exists
				# so we need to use brute force
				try:
					os.unlink("libTiCore.a")
				except:
					pass
				try:
					os.symlink(libticore,"libTiCore.a")
				except:
					pass
				os.chdir(cwd)

			# if the lib doesn't exist, force a rebuild since it's a new build
			if not os.path.exists(os.path.join(iphone_dir,'lib','libtiverify.a')):
				shutil.copy(os.path.join(template_dir,'libtiverify.a'),os.path.join(iphone_dir,'lib','libtiverify.a'))

			# compile JSS files
			cssc = csscompiler.CSSCompiler(os.path.join(project_dir,'Resources'),devicefamily,appid)
			app_stylesheet = os.path.join(iphone_dir,'Resources','stylesheet.plist')
			asf = codecs.open(app_stylesheet,'w','utf-8')
			asf.write(cssc.code)
			asf.close()
			
			if command!='simulator':
				# compile plist
				os.system("/usr/bin/plutil -convert binary1 \"%s\"" % app_stylesheet)
			
			o.write("Generated the following stylecode code:\n\n")
			o.write(cssc.code)
			o.write("\n")

			if devicefamily!=None:
				applogo = ti.generate_infoplist(infoplist,appid,devicefamily,project_dir,iphone_version)
			else:
				applogo = ti.generate_infoplist(infoplist,appid,'iphone',project_dir,iphone_version)

			# copy over the appicon
			if applogo==None and ti.properties.has_key('icon'):
				applogo = ti.properties['icon']

			try:		
				os.chdir(iphone_dir)

				deploy_target = "IPHONEOS_DEPLOYMENT_TARGET=3.1"
				device_target = 'TARGETED_DEVICE_FAMILY=1'  # this is non-sensical, but you can't pass empty string

				# clean means we need to nuke the build 
				if clean_build or force_destroy_build: 
					print "[INFO] Performing clean build"
					o.write("Performing clean build...\n")
					if os.path.exists(app_dir):
						shutil.rmtree(app_dir)

				if not os.path.exists(app_dir): os.makedirs(app_dir)

				# compile localization files
				localecompiler.LocaleCompiler(app_name,project_dir,devicefamily,command).compile()
				
				# copy any module resources
				if len(tp_module_asset_dirs)>0:
					for e in tp_module_asset_dirs:
						copy_module_resources(e[0],e[1],True)
				
				# copy any custom fonts in (only runs in simulator)
				# since we need to make them live in the bundle in simulator
				if len(custom_fonts)>0:
					for f in custom_fonts:
						print "[INFO] Detected custom font: %s" % os.path.basename(f)
						shutil.copy(f,app_dir)

				# dump out project file info
				if command!='simulator':
					dump_resources_listing(project_dir,o)
					dump_infoplist(infoplist,o)

				# copy Default.png and appicon each time so if they're 
				# changed they'll stick get picked up	
				app_icon_path = os.path.join(project_dir,'Resources','iphone',applogo)
				if not os.path.exists(app_icon_path):
					app_icon_path = os.path.join(project_dir,'Resources',applogo)
				if os.path.exists(app_icon_path):
					shutil.copy(app_icon_path,app_dir)
				defaultpng_path = os.path.join(project_dir,'Resources','iphone','Default.png')
				if not os.path.exists(defaultpng_path):
					defaultpng_path = os.path.join(project_dir,'Resources','Default.png')
				if os.path.exists(defaultpng_path):
					shutil.copy(defaultpng_path,app_dir)

				extra_args = None

				if devicefamily!=None:
					if devicefamily == 'ipad':
						device_target="TARGETED_DEVICE_FAMILY=2"
						deploy_target = "IPHONEOS_DEPLOYMENT_TARGET=3.2"
						# NOTE: this is very important to run on device -- i dunno why
						# xcode warns that 3.2 needs only armv7, but if we don't pass in 
						# armv6 we get crashes on device
						extra_args = ["VALID_ARCHS=armv6 armv7 i386"]

				def execute_xcode(sdk,extras,print_output=True):

					config = name
					if devicefamily=='ipad':
						config = "%s-iPad" % config

					args = ["xcodebuild","-target",config,"-configuration",target,"-sdk",sdk]
					if extras!=None and len(extras)>0: 
						args += extras
					args += [deploy_target,device_target]
					if extra_args!=None and len(extra_args)>0:
						args += extra_args

					o.write("Starting Xcode compile with the following arguments:\n\n")
					for arg in args: o.write("    %s\n" % arg)
					o.write("\napp_id = %s\n" % appid)
					o.write("\n\n")
					o.flush()

					if print_output:
						print "[DEBUG] compile checkpoint: %0.2f seconds" % (time.time()-start_time)
						print "[INFO] Executing XCode build..."
						print "[BEGIN_VERBOSE] Executing XCode Compiler  <span>[toggle output]</span>"

					output = run.run(args,False,False,o)

					if print_output:
						print output
						print "[END_VERBOSE]"
						sys.stdout.flush()

					o.write(output)

					# check to make sure the user doesn't have a custom build location 
					# configured in Xcode which currently causes issues with titanium
					idx = output.find("TARGET_BUILD_DIR ")
					if idx > 0:
						endidx = output.find("\n",idx)
						if endidx > 0:
							target_build_dir = dequote(output[idx+17:endidx].strip())
							if target_build_dir!=build_dir:
								o.write("+ TARGET_BUILD_DIR = %s\n" % target_build_dir)
								print "[ERROR] Your TARGET_BUILD_DIR is incorrectly set. Most likely you have configured in Xcode a customized build location. Titanium does not currently support this configuration."
								print "[ERROR] Expected dir %s, was: %s" % (build_dir,target_build_dir)
								sys.stdout.flush()
								sys.exit(1)

					# look for build error
					if output.find("** BUILD FAILED **")!=-1 or output.find("ld returned 1")!=-1 or output.find("The following build commands failed:")!=-1:
						o.write("+ Detected build failure\n")
						print "[ERROR] Build Failed. Please see output for more details"
						sys.stdout.flush()
						sys.exit(1)

					o.write("+ Looking for application binary at %s\n" % binary)

					# make sure binary exists
					if not os.path.exists(binary):
						o.write("+ Missing application binary at %s\n" % binary)
						print "[ERROR] Build Failed (Missing app at %s). Please see output for more details" % binary
						sys.stdout.flush()
						sys.exit(1)

					# look for a code signing error
					error = re.findall(r'Code Sign error:(.*)',output)
					if len(error) > 0:
						o.write("+ Detected code sign error: %s\n" % error[0])
						print "[ERROR] Code sign error: %s" % error[0].strip()
						sys.stdout.flush()
						sys.exit(1)

				# build the final release distribution
				args = []

				if command!='simulator':		
					# allow the project to have its own custom entitlements
					custom_entitlements = os.path.join(project_dir,"Entitlements.plist")
					entitlements_contents = None
					if os.path.exists(custom_entitlements):
						entitlements_contents = open(custom_entitlements).read()
						o.write("Found custom entitlements: %s\n" % custom_entitlements)
					else:
						# attempt to customize it by reading prov profile
						entitlements_contents = generate_customized_entitlements(provisioning_profile,appid,appuuid,command,o)
					o.write("Generated the following entitlements:\n\n%s\n\n" % entitlements_contents)
					f=open(os.path.join(iphone_resources_dir,'Entitlements.plist'),'w+')
					f.write(entitlements_contents)
					f.close()
					args+=["CODE_SIGN_ENTITLEMENTS = Resources/Entitlements.plist"]

				# only build if force rebuild (different version) or 
				# the app hasn't yet been built initially
				if ti.properties['guid']!=log_id or force_xcode:
					log_id = ti.properties['guid']
					f = open(version_file,'w+')
					f.write("%s,%s,%s,%s" % (template_dir,log_id,lib_hash,githash))
					f.close()

				if command == 'simulator':

					if force_rebuild or force_xcode or not os.path.exists(binary):
						execute_xcode("iphonesimulator%s" % iphone_version,["GCC_PREPROCESSOR_DEFINITIONS=__LOG__ID__=%s DEPLOYTYPE=development TI_DEVELOPMENT=1 DEBUG=1 TI_VERSION=%s" % (log_id,sdk_version)],False)

					# first make sure it's not running
					kill_simulator()

					o.write("Finishing build\n")

					# sometimes the simulator doesn't remove old log files
					# in which case we get our logging jacked - we need to remove
					# them before running the simulator
					def cleanup_app_logfiles():
						print "[DEBUG] finding old log files"
						sys.stdout.flush()
						# on OSX Snow Leopard, we can use spotlight for faster searching of log files
						results = run.run(['mdfind',
								'-onlyin',
								os.path.expanduser('~/Library/Application Support/iPhone Simulator/%s'%iphone_version),
								'-name',
								'%s.log'%log_id],True)
						if results == None: # probably not Snow Leopard
							def find_all_log_files(folder, fname):
								results = []
								for root, dirs, files in os.walk(os.path.expanduser(folder)):
									for file in files:
										if fname==file:
											fullpath = os.path.join(root, file)
											results.append(fullpath)
								return results
							for f in find_all_log_files("~/Library/Application Support/iPhone Simulator/%s"%iphone_version,'%s.log' % log_id):
								print "[DEBUG] removing old log file: %s" % f
								sys.stdout.flush()
								os.remove(f)
						else:
							for i in results.splitlines(False):
								print "[DEBUG] removing old log file: %s" % i
								os.remove(i)	

					cleanup_app_logfiles()

					sim = None

					def handler(signum, frame):
						global script_ok
						print "[INFO] Simulator is exiting"
						sys.stdout.flush()
						if not log == None:
							try:
								os.system("kill -2 %s" % str(log.pid))
							except:
								pass
						if not sim == None and signum!=3:
							try:
								os.system("kill -3 %s" % str(sim.pid))
							except:
								pass

						kill_simulator()
						script_ok = True
						sys.exit(0)

					signal.signal(signal.SIGHUP, handler)
					signal.signal(signal.SIGINT, handler)
					signal.signal(signal.SIGQUIT, handler)
					signal.signal(signal.SIGABRT, handler)
					signal.signal(signal.SIGTERM, handler)

					print "[INFO] Launching application in Simulator"

					sys.stdout.flush()
					sys.stderr.flush()

					# launch the simulator
					if devicefamily==None:
						sim = subprocess.Popen("\"%s\" launch \"%s\" %s iphone" % (iphonesim,app_dir,iphone_version),shell=True)
					else:
						sim = subprocess.Popen("\"%s\" launch \"%s\" %s %s" % (iphonesim,app_dir,iphone_version,devicefamily),shell=True)

					# activate the simulator window
					ass = os.path.join(template_dir,'iphone_sim_activate.scpt')
					cmd = "osascript \"%s\"" % ass
					os.system(cmd)

					end_time = time.time()-start_time

					print "[INFO] Launched application in Simulator (%0.2f seconds)" % end_time
					sys.stdout.flush()
					sys.stderr.flush()

					# give the simulator a bit to get started and up and running before 
					# starting the logger
					time.sleep(2)

					logger = os.path.realpath(os.path.join(template_dir,'logger.py'))

					# start the logger
					log = subprocess.Popen([
					  	logger,
						str(log_id)+'.log',
						iphone_version
					])	

					os.waitpid(sim.pid,0)

					print "[INFO] Application has exited from Simulator"

					# in this case, the user has exited the simulator itself
					# and not clicked Stop Emulator from within Developer so we kill
					# our tail log process but let simulator keep running

					if not log == None:
						try:
							os.system("kill -2 %s" % str(log.pid))
						except:
							pass

					script_ok = True


				elif command == 'install':

					args += [
						"GCC_PREPROCESSOR_DEFINITIONS=DEPLOYTYPE=test TI_TEST=1",
						"PROVISIONING_PROFILE[sdk=iphoneos*]=%s" % appuuid,
						"CODE_SIGN_IDENTITY[sdk=iphoneos*]=iPhone Developer: %s" % dist_name,
						"DEPLOYMENT_POSTPROCESSING=YES"
					]
					execute_xcode("iphoneos%s" % iphone_version,args,False)

					print "[INFO] Installing application in iTunes ... one moment"
					sys.stdout.flush()

					if os.path.exists("/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/PackageApplication"):
						o.write("+ Preparing to run /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/PackageApplication\n")
						output = run.run(["/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/PackageApplication",app_dir],True)
						o.write("+ Finished running /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/PackageApplication\n")
						if output: o.write(output)

					# for install, launch itunes with the app
					ipa = os.path.join(os.path.dirname(app_dir),"%s.ipa" % name)
					o.write("+ IPA file should be at %s\n" % ipa);

					# it appears that sometimes this command above fails on certain installs
					# or is missing. let's just open if we have it otherwise, open the app 
					# directory
					if not os.path.exists(ipa):
						# just open the app dir itself
						o.write("+ IPA didn't exist at %s\n" % ipa)
						o.write("+ Will try and open %s\n" % app_dir)
						ipa = app_dir

					cmd = "open -b com.apple.itunes \"%s\"" % ipa
					o.write("+ Executing the command: %s\n" % cmd)
					os.system(cmd)
					o.write("+ After executing the command: %s\n" % cmd)

					# now run our applescript to tell itunes to sync to get
					# the application on the phone
					ass = os.path.join(template_dir,'itunes_sync.scpt')
					cmd = "osascript \"%s\"" % ass
					o.write("+ Executing the command: %s\n" % cmd)
					os.system(cmd)
					o.write("+ After executing the command: %s\n" % cmd)

					print "[INFO] iTunes sync initiated"

					o.write("Finishing build\n")
					sys.stdout.flush()
					script_ok = True

				elif command == 'distribute':

					deploytype = "production"

					args += [
						"GCC_PREPROCESSOR_DEFINITIONS=DEPLOYTYPE=%s TI_PRODUCTION=1" % deploytype,
						"PROVISIONING_PROFILE[sdk=iphoneos*]=%s" % appuuid,
						"CODE_SIGN_IDENTITY[sdk=iphoneos*]=iPhone Distribution: %s" % dist_name,
						"DEPLOYMENT_POSTPROCESSING=YES"
					]
					execute_xcode("iphoneos%s" % iphone_version,args,False)

					# switch to app_bundle for zip
					os.chdir(build_dir)

					# starting in 4.0, apple now requires submission through XCode
					archive_uuid = str(uuid.uuid4()).upper()
					archive_dir = os.path.join(os.path.expanduser("~/Library/MobileDevice/Archived Applications"),archive_uuid)
					archive_app_dir = os.path.join(archive_dir,"%s.app" % name)
					archive_appdsym_dir = os.path.join(archive_dir,"%s.app.dSYM" % name)
					os.makedirs(archive_app_dir)
					os.makedirs(archive_appdsym_dir)
	
					os.system('ditto "%s.app" "%s"' % (name,archive_app_dir))
					os.system('ditto "%s.app.dSYM" "%s"' % (name,archive_appdsym_dir))
					
					archive_plist = os.path.join(archive_dir,'ArchiveInfo.plist')
					o.write("Writing archive plist to: %s\n\n" % archive_plist)
					
					profile_uuid = get_profile_uuid(provisioning_profile)

					os.system("/usr/bin/plutil -convert xml1 -o \"%s\" \"%s\"" % (os.path.join(archive_dir,'Info.xml.plist'),os.path.join(archive_app_dir,'Info.plist')))
					p = plistlib.readPlist(os.path.join(archive_dir,'Info.xml.plist'))
					archive_metadata = {
						'CFBundleIdentifier':p['CFBundleIdentifier'],
						'CFBundleVersion':p['CFBundleVersion'],
						'XCApplicationFilename':'%s.app' %name,
						'XCApplicationName':name,
						'XCArchivedDate': time.time() - 978307200.0,
						'XCArchiveUUID':archive_uuid,
						'XCInfoPlist' : p,
						'XCProfileUUID': profile_uuid
					}
					o.write("%s\n\n" % archive_metadata)
					plistlib.writePlist(archive_metadata,archive_plist)
					os.remove(os.path.join(archive_dir,'Info.xml.plist'))

					# open xcode + organizer after packaging
					ass = os.path.join(template_dir,'xcode_organizer.scpt')
					cmd = "osascript \"%s\"" % ass
					os.system(cmd)
					
					o.write("Finishing build\n")
					script_ok = True

			finally:
				os.chdir(cwd)
		except:
			print "[ERROR] Error: %s" % traceback.format_exc()
			if not script_ok:
				o.write("\nException detected in script:\n")
				traceback.print_exc(file=o)
				o.close()
				sys.exit(1)
			else:
				o.close()
コード例 #21
0
def main(args):
	global script_ok
	argc = len(args)
	if argc < 2 or argc==2 and (args[1]=='--help' or args[1]=='-h'):
		print "%s <command> <version> <project_dir> <appid> <name> [options]" % os.path.basename(args[0])
		print
		print "available commands: "
		print
		print "  install       install the app to itunes for testing on iphone"
		print "  simulator     build and run on the iphone simulator"
		print "  distribute    build final distribution bundle"
		print "  xcode         build from within xcode"
		print "  run           build and run app from project folder"
	
		sys.exit(1)

	print "[INFO] One moment, building ..."
	sys.stdout.flush()
	start_time = time.time()
	command = args[1].decode("utf-8")
	
	target = 'Debug'
	deploytype = 'development'
	devicefamily = 'iphone'
	debug = False
	simulator = False
	xcode_build = False
	force_xcode = False
	simtype = devicefamily

	# when you run from xcode, we'll pass xcode as the command and the 
	# xcode script will simply pass some additional args as well as xcode
	# will add some additional useful stuff to the ENVIRONMENT and we pull
	# those values out here
	if command == 'xcode':
		xcode_build = True
		src_root = os.environ['SOURCE_ROOT']
		project_dir = os.path.abspath(os.path.join(src_root,'../','../'))
		name = os.environ['PROJECT_NAME']
		target = os.environ['CONFIGURATION']
		appid = os.environ['TI_APPID']
		arch = os.environ['CURRENT_ARCH']
		sdk_name = os.environ['SDK_NAME']
		iphone_version = sdk_name.replace('iphoneos','').replace('iphonesimulator','')
		# SUPPORTED_DEVICE_FAMILIES 1 or 2 or both
		# TARGETED_DEVICE_FAMILY 1 or 2
		target_device = os.environ['TARGETED_DEVICE_FAMILY']
		if target_device == '1':
			devicefamily = 'iphone'
		elif target_device == '2':
			devicefamily = 'ipad'
		elif target_device == '1,2':
			devicefamily = 'universal'
		if arch == 'i386': 
			# simulator always indicates simulator
			deploytype = 'development'
		else:
			# if arch!=i386 indicates a build for device
			if target=='Debug':
				# non-simulator + debug build indicates test on device
				deploytype = 'test'
			else:
				# non-simulator + release build indicates package for distribution
				deploytype = 'production'
		compiler = Compiler(project_dir,appid,name,deploytype,xcode_build,devicefamily,iphone_version)
		script_ok = True
		sys.exit(0)
	else:
		# the run command is when you run from titanium using the run command
		# and it will run the project in the current directory immediately in the simulator
		# from the command line
		if command == 'run':
			if argc < 3:
				print "Usage: %s run <project_dir> [ios_version]" % os.path.basename(args[0])
				sys.exit(1)
			if argc == 3:
				iphone_version = check_iphone_sdk('4.0')
			else:
				iphone_version = dequote(args[3].decode("utf-8"))
			project_dir = os.path.expanduser(dequote(args[2].decode("utf-8")))
			iphonesim = os.path.abspath(os.path.join(template_dir,'iphonesim'))
			iphone_dir = os.path.abspath(os.path.join(project_dir,'build','iphone'))
			tiapp_xml = os.path.join(project_dir,'tiapp.xml')
			ti = TiAppXML(tiapp_xml)
			appid = ti.properties['id']
			name = ti.properties['name']
			command = 'simulator' # switch it so that the rest of the stuff works
		else:
			iphone_version = dequote(args[2].decode("utf-8"))
			iphonesim = os.path.abspath(os.path.join(template_dir,'iphonesim'))
			project_dir = os.path.expanduser(dequote(args[3].decode("utf-8")))
			appid = dequote(args[4].decode("utf-8"))
			name = dequote(args[5].decode("utf-8"))
			tiapp_xml = os.path.join(project_dir,'tiapp.xml')
			ti = TiAppXML(tiapp_xml)
			
		app_name = make_app_name(name)
		iphone_dir = os.path.abspath(os.path.join(project_dir,'build','iphone'))
		project_xcconfig = os.path.join(iphone_dir,'project.xcconfig')
		target = 'Release'
		ostype = 'os'
		version_file = None
		log_id = None
		provisioning_profile = None
		debug_host = None
		debug_port = None
		debughost = None
		
		# starting in 1.4, you don't need to actually keep the build/iphone directory
		# if we don't find it, we'll just simply re-generate it
		if not os.path.exists(iphone_dir):
			from iphone import IPhone
			print "[INFO] Detected missing project but that's OK. re-creating it..."
			iphone_creator = IPhone(name,appid)
			iphone_creator.create(iphone_dir,True)
			sys.stdout.flush()
			
		# we use different arguments dependent on the command
		# pluck those out here
		if command == 'distribute':
			iphone_version = check_iphone_sdk(iphone_version)
			link_version = iphone_version
			appuuid = dequote(args[6].decode("utf-8"))
			dist_name = dequote(args[7].decode("utf-8"))
			output_dir = os.path.expanduser(dequote(args[8].decode("utf-8")))
			if argc > 9:
				devicefamily = dequote(args[9].decode("utf-8"))
			deploytype = 'production'
		elif command == 'simulator':
			link_version = check_iphone_sdk(iphone_version)
			deploytype = 'development'
			debug = True
			simulator = True
			target = 'Debug'
			ostype = 'simulator'
			if argc > 6:
				devicefamily = dequote(args[6].decode("utf-8"))
			if argc > 7:
				simtype = dequote(args[7].decode("utf-8"))
			else:
				# 'universal' helpfully translates into iPhone here... just in case.
				simtype = devicefamily
			if argc > 8:
				# this is host:port from the debugger
				debughost = dequote(args[8].decode("utf-8"))
				if debughost=='':
					debughost = None
				else:
					debughost,debugport = debughost.split(":")
		elif command == 'install':
			iphone_version = check_iphone_sdk(iphone_version)
			link_version = iphone_version
			appuuid = dequote(args[6].decode("utf-8"))
			dist_name = dequote(args[7].decode("utf-8"))
			if argc > 8:
				devicefamily = dequote(args[8].decode("utf-8"))
			if argc > 9:
				# this is host:port from the debugger
				debughost = dequote(args[9].decode("utf-8"))
				if debughost=='':
					debughost=None
				else:
					debughost,debugport = debughost.split(":")
			deploytype = 'test'
		
		# setup up the useful directories we need in the script
		build_out_dir = os.path.abspath(os.path.join(iphone_dir,'build'))
		build_dir = os.path.abspath(os.path.join(build_out_dir,'%s-iphone%s'%(target,ostype)))
		app_dir = os.path.abspath(os.path.join(build_dir,name+'.app'))
		binary = os.path.join(app_dir,name)
		sdk_version = os.path.basename(os.path.abspath(os.path.join(template_dir,'../')))
		iphone_resources_dir = os.path.join(iphone_dir,'Resources')
		version_file = os.path.join(iphone_resources_dir,'.version')
		force_rebuild = read_project_version(project_xcconfig)!=sdk_version or not os.path.exists(version_file)
		infoplist = os.path.join(iphone_dir,'Info.plist')
		githash = None
		custom_fonts = []

		# if we're not running in the simulator we want to clean out the build directory
		if command!='simulator' and os.path.exists(build_out_dir):
			shutil.rmtree(build_out_dir)
		if not os.path.exists(build_out_dir): 
			os.makedirs(build_out_dir)
		# write out the build log, useful for debugging
		o = codecs.open(os.path.join(build_out_dir,'build.log'),'w',encoding='utf-8')
		def log(msg):
			print msg
			o.write(msg)
		try:
			buildtime = datetime.datetime.now()
			o.write("%s\n" % ("="*80))
			o.write("Appcelerator Titanium Diagnostics Build Log\n")
			o.write("The contents of this file are useful to send to Appcelerator Support if\n")
			o.write("reporting an issue to help us understand your environment, build settings\n")
			o.write("and aid in debugging. Please attach this log to any issue that you report.\n")
			o.write("%s\n\n" % ("="*80))
			o.write("Starting build at %s\n\n" % buildtime.strftime("%m/%d/%y %H:%M"))
			
			# write out the build versions info
			versions_txt = read_config(os.path.join(template_dir,'..','version.txt'))
			o.write("Build details:\n\n")
			for key in versions_txt:
				o.write("   %s=%s\n" % (key,versions_txt[key]))
			o.write("\n\n")
			
			if versions_txt.has_key('githash'): 
				githash = versions_txt['githash']
				
			o.write("Script arguments:\n")
			for arg in args:
				o.write(unicode("   %s\n" % arg, 'utf-8'))
			o.write("\n")
			o.write("Building from: %s\n" % template_dir)
			o.write("Platform: %s\n\n" % platform.version())

			# print out path to debug
			xcode_path=run.run(["/usr/bin/xcode-select","-print-path"],True,False)
			if xcode_path:
				o.write("Xcode path is: %s\n" % xcode_path)
			else:
				o.write("Xcode path undetermined\n")

			# find the module directory relative to the root of the SDK	
			titanium_dir = os.path.abspath(os.path.join(template_dir,'..','..','..','..'))
			tp_module_dir = os.path.abspath(os.path.join(titanium_dir,'modules','iphone'))
			force_destroy_build = command!='simulator'

			detector = ModuleDetector(project_dir)
			missing_modules, modules = detector.find_app_modules(ti, 'iphone')
			module_lib_search_path = []
			module_asset_dirs = []
			
			# search for modules that the project is using
			# and make sure we add them to the compile
			for module in modules:
				module_id = module.manifest.moduleid.lower()
				module_version = module.manifest.version
				module_lib_name = ('lib%s.a' % module_id).lower()
				# check first in the local project
				local_module_lib = os.path.join(project_dir, 'modules', 'iphone', module_lib_name)
				local = False
				if os.path.exists(local_module_lib):
					module_lib_search_path.append([module_lib_name, local_module_lib])
					local = True
					log("[INFO] Detected third-party module: %s" % (local_module_lib))
				else:
					if module.lib is None:
						module_lib_path = module.get_resource(module_lib_name)
						log("[ERROR] Third-party module: %s/%s missing library at %s" % (module_id, module_version, module_lib_path))
						sys.exit(1)
					module_lib_search_path.append([module_lib_name, os.path.abspath(module.lib).rsplit('/',1)[0]])
					log("[INFO] Detected third-party module: %s/%s" % (module_id, module_version))
				force_xcode = True

				if not local:
					# copy module resources
					img_dir = module.get_resource('assets', 'images')
					if os.path.exists(img_dir):
						dest_img_dir = os.path.join(app_dir, 'modules', module_id, 'images')
						if not os.path.exists(dest_img_dir):
							os.makedirs(dest_img_dir)
						module_asset_dirs.append([img_dir, dest_img_dir])

					# copy in any module assets
					module_assets_dir = module.get_resource('assets')
					if os.path.exists(module_assets_dir): 
						module_dir = os.path.join(app_dir, 'modules', module_id)
						module_asset_dirs.append([module_assets_dir, module_dir])


			print "[INFO] Titanium SDK version: %s" % sdk_version
			print "[INFO] iPhone Device family: %s" % devicefamily
			print "[INFO] iPhone SDK version: %s" % iphone_version
			
			if simulator:
				print "[INFO] iPhone simulated device: %s" % simtype
				# during simulator we need to copy in standard built-in module files
				# since we might not run the compiler on subsequent launches
				for module_name in ('facebook','ui'):
					img_dir = os.path.join(template_dir,'modules',module_name,'images')
					dest_img_dir = os.path.join(app_dir,'modules',module_name,'images')
					if not os.path.exists(dest_img_dir):
						os.makedirs(dest_img_dir)
					module_asset_dirs.append([img_dir,dest_img_dir])

				# when in simulator since we point to the resources directory, we need
				# to explicitly copy over any files
				ird = os.path.join(project_dir,'Resources','iphone')
				if os.path.exists(ird): 
					module_asset_dirs.append([ird,app_dir])
				
				for ext in ('ttf','otf'):
					for f in glob.glob('%s/*.%s' % (os.path.join(project_dir,'Resources'),ext)):
						custom_fonts.append(f)
					

			if not simulator:
				version = ti.properties['version']
				# we want to make sure in debug mode the version always changes
				version = "%s.%d" % (version,time.time())
				ti.properties['version']=version
				pp = os.path.expanduser("~/Library/MobileDevice/Provisioning Profiles/%s.mobileprovision" % appuuid)
				provisioning_profile = read_provisioning_profile(pp,o)
			
			
			def write_debugger_plist(debuggerplist):
				debugger_tmpl = os.path.join(template_dir,'debugger.plist')
				plist = codecs.open(debugger_tmpl, encoding='utf-8').read()
				if debughost:
					plist = plist.replace('__DEBUGGER_HOST__',debughost)
					plist = plist.replace('__DEBUGGER_PORT__',debugport)
				else:
					plist = plist.replace('__DEBUGGER_HOST__','')
					plist = plist.replace('__DEBUGGER_PORT__','')
				pf = codecs.open(debuggerplist,'w', encoding='utf-8')
				pf.write(plist)
				pf.close()
				
				
# TODO:				
# This code is used elsewhere, as well.  We should move stuff like this to
# a common file.
			def write_info_plist(infoplist_tmpl):
				plist = codecs.open(infoplist_tmpl, encoding='utf-8').read()
				plist = plist.replace('__PROJECT_NAME__',name)
				plist = plist.replace('__PROJECT_ID__',appid)
				plist = plist.replace('__URL__',appid)
				urlscheme = name.replace('.','_').replace(' ','').lower()
				plist = plist.replace('__URLSCHEME__',urlscheme)
				if ti.has_app_property('ti.facebook.appid'):
					fbid = ti.get_app_property('ti.facebook.appid')
					plist = plist.replace('__ADDITIONAL_URL_SCHEMES__', '<string>fb%s</string>' % fbid)
				else:
					plist = plist.replace('__ADDITIONAL_URL_SCHEMES__','')
				pf = codecs.open(infoplist,'w', encoding='utf-8')
				pf.write(plist)
				pf.close()			

			# if the user has a Info.plist in their project directory, consider
			# that a custom override
			infoplist_tmpl = os.path.join(project_dir,'Info.plist')
			if os.path.exists(infoplist_tmpl):
				shutil.copy(infoplist_tmpl,infoplist)
			else:
				infoplist_tmpl = os.path.join(template_dir,'Info.plist')
				write_info_plist(infoplist_tmpl)

			applogo = None
			clean_build = False

			# check to see if the appid is different (or not specified) - we need to re-generate
			if read_project_appid(project_xcconfig)!=appid or not infoplist_has_appid(infoplist,appid):
				clean_build = True
				force_xcode = True


			new_lib_hash = None
			lib_hash = None	
			existing_git_hash = None

			# this code simply tries and detect if we're building a different
			# version of the project (or same version but built from different git hash)
			# and if so, make sure we force rebuild so to propograte any code changes in
			# source code (either upgrade or downgrade)
			if os.path.exists(app_dir):
				if os.path.exists(version_file):
					line = open(version_file).read().strip()
					lines = line.split(",")
					v = lines[0]
					log_id = lines[1]
					if len(lines) > 2:
						lib_hash = lines[2]
						existing_git_hash = lines[3]
					if lib_hash==None:
						force_rebuild = True
					else:
						if template_dir==v and force_rebuild==False:
							force_rebuild = False
						else:
							log_id = None
				else:
					force_rebuild = True

			else:
				force_rebuild = True

			o.write("\ngithash=%s, existing_git_hash=%s\n" %(githash,existing_git_hash))
				
			if githash!=existing_git_hash:
				force_rebuild = True

			# we want to read the md5 of the libTiCore.a library since it must match
			# the current one we're building and if not, we need to force a rebuild since
			# that means we've copied in a different version of the library and we need
			# to rebuild clean to avoid linking errors
			source_lib=os.path.join(template_dir,'libTiCore.a')
			fd = open(source_lib,'rb')
			m = hashlib.md5()
			m.update(fd.read(1024)) # just read 1K, it's binary
			new_lib_hash = m.hexdigest()
			fd.close()
			
			if new_lib_hash!=lib_hash:
				force_rebuild=True
				o.write("forcing rebuild since libhash (%s) not matching (%s)\n" % (lib_hash,new_lib_hash))

			lib_hash=new_lib_hash

			# when we force rebuild, we need to re-compile and re-copy source, libs etc
			if force_rebuild:
				o.write("Performing full rebuild\n")
				print "[INFO] Performing full rebuild. This will take a little bit. Hold tight..."
				sys.stdout.flush()
				project = Projector(name,sdk_version,template_dir,project_dir,appid)
				project.create(template_dir,iphone_dir)	
				force_xcode = True
				if os.path.exists(app_dir): shutil.rmtree(app_dir)
				# we have to re-copy if we have a custom version
				write_info_plist(infoplist_tmpl)
				# since compiler will generate the module dependencies, we need to 
				# attempt to compile to get it correct for the first time.
				compiler = Compiler(project_dir,appid,name,deploytype,xcode_build,devicefamily,iphone_version,True)
			else:
				contents="TI_VERSION=%s\n"% sdk_version
				contents+="TI_SDK_DIR=%s\n" % template_dir.replace(sdk_version,'$(TI_VERSION)')
				contents+="TI_APPID=%s\n" % appid
				contents+="OTHER_LDFLAGS[sdk=iphoneos4*]=$(inherited) -weak_framework iAd\n"
				contents+="OTHER_LDFLAGS[sdk=iphonesimulator4*]=$(inherited) -weak_framework iAd\n"
				contents+="#include \"module\"\n"
				xcconfig = open(project_xcconfig,'w+')
				xccontents = xcconfig.read()
				if contents!=xccontents:
					o.write("writing contents of %s:\n\n%s\n" % (project_xcconfig,contents))
					o.write("old contents\n\n%s\n" % (xccontents))
					xcconfig.write(contents)
					xcconfig.close()
				else:
					o.write("Skipping writing contents of xcconfig %s\n" % project_xcconfig)

			# write out any modules into the xcode project
			# this must be done after project create above or this will be overriden
			if len(module_lib_search_path)>0:
				proj = PBXProj()
				xcode_proj = os.path.join(iphone_dir,'%s.xcodeproj'%name,'project.pbxproj')
				current_xcode = open(xcode_proj).read()
				for tp in module_lib_search_path:
					proj.add_static_library(tp[0],tp[1])
				out = proj.parse(xcode_proj)
				# since xcode changes can be destructive, only write as necessary (if changed)
				if current_xcode!=out:
					xo = open(xcode_proj,'w')
					xo.write(out)
					xo.close()

			cwd = os.getcwd()

			# check to see if the symlink exists and that it points to the
			# right version of the library
			libticore = os.path.join(template_dir,'libTiCore.a')
			make_link = True
			symlink = os.path.join(iphone_dir,'lib','libTiCore.a')
			if os.path.islink(symlink):
				path = os.path.realpath(symlink)
				if path.find(sdk_version) > 0:
					make_link = False
			if make_link:
				libdir = os.path.join(iphone_dir,'lib')
				if not os.path.exists(libdir): os.makedirs(libdir)
				os.chdir(libdir)
				# a broken link will not return true on os.path.exists
				# so we need to use brute force
				try:
					os.unlink("libTiCore.a")
				except:
					pass
				try:
					os.symlink(libticore,"libTiCore.a")
				except:
					pass
				os.chdir(cwd)

			# if the lib doesn't exist, force a rebuild since it's a new build
			if not os.path.exists(os.path.join(iphone_dir,'lib','libtiverify.a')):
				shutil.copy(os.path.join(template_dir,'libtiverify.a'),os.path.join(iphone_dir,'lib','libtiverify.a'))

			if not os.path.exists(os.path.join(iphone_dir,'lib','libti_ios_debugger.a')):
				shutil.copy(os.path.join(template_dir,'libti_ios_debugger.a'),os.path.join(iphone_dir,'lib','libti_ios_debugger.a'))

			# compile JSS files
			cssc = csscompiler.CSSCompiler(os.path.join(project_dir,'Resources'),devicefamily,appid)
			app_stylesheet = os.path.join(iphone_dir,'Resources','stylesheet.plist')
			asf = codecs.open(app_stylesheet,'w','utf-8')
			asf.write(cssc.code)
			asf.close()

			# compile debugger file
			debug_plist = os.path.join(iphone_dir,'Resources','debugger.plist')
			write_debugger_plist(debug_plist)

			if command!='simulator':
				# compile plist into binary format so it's faster to load
				# we can be slow on simulator
				os.system("/usr/bin/plutil -convert binary1 \"%s\"" % app_stylesheet)
			
			o.write("Generated the following stylecode code:\n\n")
			o.write(cssc.code)
			o.write("\n")

			# generate the Info.plist file with the appropriate device family
			if devicefamily!=None:
				applogo = ti.generate_infoplist(infoplist,appid,devicefamily,project_dir,iphone_version)
			else:
				applogo = ti.generate_infoplist(infoplist,appid,'iphone',project_dir,iphone_version)

			# copy over the appicon
			if applogo==None and ti.properties.has_key('icon'):
				applogo = ti.properties['icon']
				
			# attempt to load any compiler plugins
			if len(ti.properties['plugins']) > 0:
				local_compiler_dir = os.path.abspath(os.path.join(project_dir,'plugins'))
				tp_compiler_dir = os.path.abspath(os.path.join(titanium_dir,'plugins'))
				if not os.path.exists(tp_compiler_dir) and not os.path.exists(local_compiler_dir):
					o.write("+ Missing plugins directory at %s\n" % tp_compiler_dir)
					print "[ERROR] Build Failed (Missing plugins directory). Please see output for more details"
					sys.stdout.flush()
					sys.exit(1)
				compiler_config = {
					'platform':'ios',
					'devicefamily':devicefamily,
					'simtype':simtype,
					'tiapp':ti,
					'project_dir':project_dir,
					'titanium_dir':titanium_dir,
					'appid':appid,
					'iphone_version':iphone_version,
					'template_dir':template_dir,
					'project_name':name,
					'command':command,
					'deploytype':deploytype,
					'build_dir':build_dir,
					'app_name':app_name,
					'app_dir':app_dir,
					'iphone_dir':iphone_dir
				}
				for plugin in ti.properties['plugins']:
					local_plugin_file = os.path.join(local_compiler_dir,plugin['name'],'plugin.py')
					plugin_file = os.path.join(tp_compiler_dir,plugin['name'],plugin['version'],'plugin.py')
					if not os.path.exists(local_plugin_file) and not os.path.exists(plugin_file):
						o.write("+ Missing plugin at %s (checked %s also)\n" % (plugin_file,local_plugin_file))
						print "[ERROR] Build Failed (Missing plugin for %s). Please see output for more details" % plugin['name']
						sys.stdout.flush()
						sys.exit(1)
					o.write("+ Detected plugin: %s/%s\n" % (plugin['name'],plugin['version']))
					print "[INFO] Detected compiler plugin: %s/%s" % (plugin['name'],plugin['version'])
					code_path = plugin_file
					if os.path.exists(local_plugin_file):	
						code_path = local_plugin_file
					o.write("+ Loading compiler plugin at %s\n" % code_path)
					compiler_config['plugin']=plugin
					fin = open(code_path, 'rb')
					m = hashlib.md5()
					m.update(open(code_path,'rb').read()) 
					code_hash = m.hexdigest()
					p = imp.load_source(code_hash, code_path, fin)
					p.compile(compiler_config)
					fin.close()
					
			try:		
				os.chdir(iphone_dir)

				# we always target backwards to 3.1 even when we use a later
				# version iOS SDK. this ensures our code will run on old devices
				# no matter which SDK we compile with
				deploy_target = "IPHONEOS_DEPLOYMENT_TARGET=3.1"
				device_target = 'TARGETED_DEVICE_FAMILY=1'  # this is non-sensical, but you can't pass empty string

				# clean means we need to nuke the build 
				if clean_build or force_destroy_build: 
					print "[INFO] Performing clean build"
					o.write("Performing clean build...\n")
					if os.path.exists(app_dir):
						shutil.rmtree(app_dir)

				if not os.path.exists(app_dir): os.makedirs(app_dir)

				# compile localization files
				# Using app_name here will cause the locale to be put in the WRONG bundle!!
				localecompiler.LocaleCompiler(name,project_dir,devicefamily,command).compile()
				
				# copy any module resources
				if len(module_asset_dirs)>0:
					for e in module_asset_dirs:
						copy_module_resources(e[0],e[1],True)
				
				# copy any custom fonts in (only runs in simulator)
				# since we need to make them live in the bundle in simulator
				if len(custom_fonts)>0:
					for f in custom_fonts:
						print "[INFO] Detected custom font: %s" % os.path.basename(f)
						shutil.copy(f,app_dir)

				# dump out project file info
				if command!='simulator':
					dump_resources_listing(project_dir,o)
					dump_infoplist(infoplist,o)

				# copy Default.png and appicon each time so if they're 
				# changed they'll stick get picked up	
				app_icon_path = os.path.join(project_dir,'Resources','iphone',applogo)
				if not os.path.exists(app_icon_path):
					app_icon_path = os.path.join(project_dir,'Resources',applogo)
				if os.path.exists(app_icon_path):
					shutil.copy(app_icon_path,app_dir)
				defaultpng_path = os.path.join(project_dir,'Resources','iphone','Default.png')
				if not os.path.exists(defaultpng_path):
					defaultpng_path = os.path.join(project_dir,'Resources','Default.png')
				if os.path.exists(defaultpng_path):
					shutil.copy(defaultpng_path,app_dir)

				extra_args = None

				if devicefamily!=None:
					# Meet the minimum requirements for ipad when necessary
					if devicefamily == 'ipad' or devicefamily == 'universal':
						device_target="TARGETED_DEVICE_FAMILY=2"
						# iPad requires at a minimum 3.2 (not 3.1 default)
						if devicefamily == 'ipad':
							deploy_target = "IPHONEOS_DEPLOYMENT_TARGET=3.2"
						# NOTE: this is very important to run on device -- i dunno why
						# xcode warns that 3.2 needs only armv7, but if we don't pass in 
						# armv6 we get crashes on device
						extra_args = ["VALID_ARCHS=armv6 armv7 i386"]
					# Additionally, if we're universal, change the device family target
					if devicefamily == 'universal':
						device_target="TARGETED_DEVICE_FAMILY=1,2"

				def execute_xcode(sdk,extras,print_output=True):

					config = name
					if devicefamily=='ipad':
						config = "%s-iPad" % config
					if devicefamily=='universal':
						config = "%s-universal" % config

					# these are the arguments for running a command line xcode build
					args = ["xcodebuild","-target",config,"-configuration",target,"-sdk",sdk]
					if extras!=None and len(extras)>0: 
						args += extras
					args += [deploy_target,device_target]
					if extra_args!=None and len(extra_args)>0:
						args += extra_args

					o.write("Starting Xcode compile with the following arguments:\n\n")
					for arg in args: o.write("    %s\n" % arg)
					o.write("\napp_id = %s\n" % appid)
					o.write("\n\n")
					o.flush()

					if print_output:
						print "[DEBUG] compile checkpoint: %0.2f seconds" % (time.time()-start_time)
						print "[INFO] Executing XCode build..."
						print "[BEGIN_VERBOSE] Executing XCode Compiler  <span>[toggle output]</span>"

					output = run.run(args,False,False,o)

					if print_output:
						print output
						print "[END_VERBOSE]"
						sys.stdout.flush()

					# Output already written by run.run
					#o.write(output)

					# check to make sure the user doesn't have a custom build location 
					# configured in Xcode which currently causes issues with titanium
					idx = output.find("TARGET_BUILD_DIR ")
					if idx > 0:
						endidx = output.find("\n",idx)
						if endidx > 0:
							target_build_dir = dequote(output[idx+17:endidx].strip())
							if target_build_dir!=build_dir:
								o.write("+ TARGET_BUILD_DIR = %s\n" % target_build_dir)
								print "[ERROR] Your TARGET_BUILD_DIR is incorrectly set. Most likely you have configured in Xcode a customized build location. Titanium does not currently support this configuration."
								print "[ERROR] Expected dir %s, was: %s" % (build_dir,target_build_dir)
								sys.stdout.flush()
								sys.exit(1)

					# look for build error
					if output.find("** BUILD FAILED **")!=-1 or output.find("ld returned 1")!=-1 or output.find("The following build commands failed:")!=-1:
						o.write("+ Detected build failure\n")
						print "[ERROR] Build Failed. Please see output for more details"
						sys.stdout.flush()
						sys.exit(1)

					o.write("+ Looking for application binary at %s\n" % binary)

					# make sure binary exists
					if not os.path.exists(binary):
						o.write("+ Missing application binary at %s\n" % binary)
						print "[ERROR] Build Failed (Missing app at %s). Please see output for more details" % binary
						sys.stdout.flush()
						sys.exit(1)

					# look for a code signing error
					error = re.findall(r'Code Sign error:(.*)',output)
					if len(error) > 0:
						o.write("+ Detected code sign error: %s\n" % error[0])
						print "[ERROR] Code sign error: %s" % error[0].strip()
						sys.stdout.flush()
						sys.exit(1)

				# build the final release distribution
				args = []

				if command!='simulator':		
					# allow the project to have its own custom entitlements
					custom_entitlements = os.path.join(project_dir,"Entitlements.plist")
					entitlements_contents = None
					if os.path.exists(custom_entitlements):
						entitlements_contents = open(custom_entitlements).read()
						o.write("Found custom entitlements: %s\n" % custom_entitlements)
					else:
						# attempt to customize it by reading prov profile
						entitlements_contents = generate_customized_entitlements(provisioning_profile,appid,appuuid,command,o)
					o.write("Generated the following entitlements:\n\n%s\n\n" % entitlements_contents)
					f=open(os.path.join(iphone_resources_dir,'Entitlements.plist'),'w+')
					f.write(entitlements_contents)
					f.close()
					args+=["CODE_SIGN_ENTITLEMENTS=Resources/Entitlements.plist"]

				# only build if force rebuild (different version) or 
				# the app hasn't yet been built initially
				if ti.properties['guid']!=log_id or force_xcode:
					log_id = ti.properties['guid']
					f = open(version_file,'w+')
					f.write("%s,%s,%s,%s" % (template_dir,log_id,lib_hash,githash))
					f.close()

				# this is a simulator build
				if command == 'simulator':

					debugstr = ''
					if debughost:
						debugstr = 'DEBUGGER_ENABLED=1'
					
					if force_rebuild or force_xcode or not os.path.exists(binary):
						execute_xcode("iphonesimulator%s" % link_version,["GCC_PREPROCESSOR_DEFINITIONS=__LOG__ID__=%s DEPLOYTYPE=development TI_DEVELOPMENT=1 DEBUG=1 TI_VERSION=%s %s" % (log_id,sdk_version,debugstr)],False)

					# first make sure it's not running
					kill_simulator()

					o.write("Finishing build\n")

					# sometimes the simulator doesn't remove old log files
					# in which case we get our logging jacked - we need to remove
					# them before running the simulator
					def cleanup_app_logfiles():
						print "[DEBUG] finding old log files"
						sys.stdout.flush()
						# on OSX Snow Leopard, we can use spotlight for faster searching of log files
						results = run.run(['mdfind',
								'-onlyin',
								os.path.expanduser('~/Library/Application Support/iPhone Simulator/%s'%iphone_version),
								'-name',
								'%s.log'%log_id],True)
						if results == None: # probably not Snow Leopard
							def find_all_log_files(folder, fname):
								results = []
								for root, dirs, files in os.walk(os.path.expanduser(folder)):
									for file in files:
										if fname==file:
											fullpath = os.path.join(root, file)
											results.append(fullpath)
								return results
							for f in find_all_log_files("~/Library/Application Support/iPhone Simulator/%s"%iphone_version,'%s.log' % log_id):
								print "[DEBUG] removing old log file: %s" % f
								sys.stdout.flush()
								os.remove(f)
						else:
							for i in results.splitlines(False):
								print "[DEBUG] removing old log file: %s" % i
								os.remove(i)	

					cleanup_app_logfiles()

					sim = None

					# this handler will simply catch when the simulator exits
					# so we can exit this script
					def handler(signum, frame):
						global script_ok
						print "[INFO] Simulator is exiting"
						sys.stdout.flush()
						if not log == None:
							try:
								os.system("kill -2 %s" % str(log.pid))
							except:
								pass
						if not sim == None and signum!=3:
							try:
								os.system("kill -3 %s" % str(sim.pid))
							except:
								pass

						kill_simulator()
						script_ok = True
						sys.exit(0)

					# make sure we're going to stop this script whenever 
					# the simulator exits
					signal.signal(signal.SIGHUP, handler)
					signal.signal(signal.SIGINT, handler)
					signal.signal(signal.SIGQUIT, handler)
					signal.signal(signal.SIGABRT, handler)
					signal.signal(signal.SIGTERM, handler)

					print "[INFO] Launching application in Simulator"

					sys.stdout.flush()
					sys.stderr.flush()

					# set the DYLD_FRAMEWORK_PATH environment variable for the following Popen iphonesim command
					# this allows the XCode developer folder to be arbitrarily named
					xcodeselectpath = os.popen("/usr/bin/xcode-select -print-path").readline().rstrip('\n')
					iphoneprivateframeworkspath = xcodeselectpath + '/Platforms/iPhoneSimulator.platform/Developer/Library/PrivateFrameworks'
					os.putenv('DYLD_FRAMEWORK_PATH', iphoneprivateframeworkspath)

					# launch the simulator
					if devicefamily==None:
						sim = subprocess.Popen("\"%s\" launch \"%s\" %s iphone" % (iphonesim,app_dir,iphone_version),shell=True)
					else:
						sim = subprocess.Popen("\"%s\" launch \"%s\" %s %s" % (iphonesim,app_dir,iphone_version,simtype),shell=True)

					# activate the simulator window - we use a OSA script to 
					# cause the simulator window to come into the foreground (otherwise
					# it will be behind Titanium Developer window)
					ass = os.path.join(template_dir,'iphone_sim_activate.scpt')
					cmd = "osascript \"%s\" 2>/dev/null" % ass
					os.system(cmd)

					end_time = time.time()-start_time

					print "[INFO] Launched application in Simulator (%0.2f seconds)" % end_time
					sys.stdout.flush()
					sys.stderr.flush()

					# give the simulator a bit to get started and up and running before 
					# starting the logger
					time.sleep(2)

					logger = os.path.realpath(os.path.join(template_dir,'logger.py'))

					# start the logger tail process. this will simply read the output
					# from the logs and stream them back to Titanium Developer on the console
					log = subprocess.Popen([
					  	logger,
						str(log_id)+'.log',
						iphone_version
					])	

					# wait (blocking this script) until the simulator exits	
					try:
						os.waitpid(sim.pid,0)
					except SystemExit:
						# If the user terminates the app here, it's via a
						# soft kill of some kind (i.e. like what TiDev does)
						# and so we should suppress the usual error message.
						# Fixes #2086
						pass

					print "[INFO] Application has exited from Simulator"

					# in this case, the user has exited the simulator itself
					# and not clicked Stop Emulator from within Developer so we kill
					# our tail log process but let simulator keep running
					if not log == None:
						try:
							os.system("kill -2 %s" % str(log.pid))
						except:
							pass

					script_ok = True
					
				###########################################################################	
				# END OF SIMULATOR COMMAND	
				###########################################################################	
				
				
				#
				# this command is run for installing an app on device
				#
				elif command == 'install':

					debugstr = ''
					if debughost:
						debugstr = 'DEBUGGER_ENABLED=1'
						
					args += [
						"GCC_PREPROCESSOR_DEFINITIONS=DEPLOYTYPE=test TI_TEST=1 %s" % debugstr,
						"PROVISIONING_PROFILE=%s" % appuuid,
						"CODE_SIGN_IDENTITY=iPhone Developer: %s" % dist_name,
						"DEPLOYMENT_POSTPROCESSING=YES"
					]
					execute_xcode("iphoneos%s" % iphone_version,args,False)

					print "[INFO] Installing application in iTunes ... one moment"
					sys.stdout.flush()

					if os.path.exists("/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/PackageApplication"):
						o.write("+ Preparing to run /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/PackageApplication\n")
						output = run.run(["/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/PackageApplication",app_dir],True)
						o.write("+ Finished running /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/PackageApplication\n")
						if output: o.write(output)

					# for install, launch itunes with the app
					ipa = os.path.join(os.path.dirname(app_dir),"%s.ipa" % name)
					o.write("+ IPA file should be at %s\n" % ipa);

					# it appears that sometimes this command above fails on certain installs
					# or is missing. let's just open if we have it otherwise, open the app 
					# directory
					if not os.path.exists(ipa):
						# just open the app dir itself
						o.write("+ IPA didn't exist at %s\n" % ipa)
						o.write("+ Will try and open %s\n" % app_dir)
						ipa = app_dir

					# to force iTunes to install our app, we simply open the IPA
					# file in itunes
					cmd = "open -b com.apple.itunes \"%s\"" % ipa
					o.write("+ Executing the command: %s\n" % cmd)
					os.system(cmd)
					o.write("+ After executing the command: %s\n" % cmd)

					# now run our applescript to tell itunes to sync to get
					# the application on the phone
					ass = os.path.join(template_dir,'itunes_sync.scpt')
					cmd = "osascript \"%s\"" % ass
					o.write("+ Executing the command: %s\n" % cmd)
					os.system(cmd)
					o.write("+ After executing the command: %s\n" % cmd)

					print "[INFO] iTunes sync initiated"

					o.write("Finishing build\n")
					sys.stdout.flush()
					script_ok = True
					
				###########################################################################	
				# END OF INSTALL COMMAND	
				###########################################################################	

				#
				# this command is run for packaging an app for distribution
				#
				elif command == 'distribute':

					deploytype = "production"

					args += [
						"GCC_PREPROCESSOR_DEFINITIONS=DEPLOYTYPE=%s TI_PRODUCTION=1" % deploytype,
						"PROVISIONING_PROFILE=%s" % appuuid,
						"CODE_SIGN_IDENTITY=iPhone Distribution: %s" % dist_name,
						"DEPLOYMENT_POSTPROCESSING=YES"
					]
					execute_xcode("iphoneos%s" % iphone_version,args,False)

					# switch to app_bundle for zip
					os.chdir(build_dir)
					if xcode_version() >= 4.0:
						distribute_xc4(name, applogo, o)
					else:
						distribute_xc3(uuid, provisioning_profile, name, o)

					# open xcode + organizer after packaging
					# Have to force the right xcode open...
					xc_path = os.path.join(run.run(['xcode-select','-print-path'],True,False).rstrip(),'Applications','Xcode.app')
					o.write("Launching xcode: %s\n" % xc_path)
					os.system('open -a %s' % xc_path)
					
					ass = os.path.join(template_dir,'xcode_organizer.scpt')
					cmd = "osascript \"%s\"" % ass
					os.system(cmd)
					
					o.write("Finishing build\n")
					script_ok = True

				###########################################################################	
				# END OF DISTRIBUTE COMMAND	
				###########################################################################	

			finally:
				os.chdir(cwd)
		except:
			print "[ERROR] Error: %s" % traceback.format_exc()
			if not script_ok:
				o.write("\nException detected in script:\n")
				traceback.print_exc(file=o)
				o.close()
				sys.exit(1)
			else:
				o.close()
コード例 #22
0
def generate_images(network_pkl, target_fname):
    tflib.init_tf()
    print('Loading networks from "%s"...' % network_pkl)
    _G, _D, Gs = pretrained_networks.load_networks(network_pkl)

    # # Render images for a given dlatent vector.
    if target_fname is not None:
        target_pil = PIL.Image.open(target_fname)
        w, h = target_pil.size
        s = min(w, h)
        target_pil = target_pil.crop(
            ((w - s) // 2, (h - s) // 2, (w + s) // 2, (h + s) // 2))
        target_pil = target_pil.convert('RGB')
        target_pil = target_pil.resize(
            (Gs.output_shape[3], Gs.output_shape[2]), PIL.Image.ANTIALIAS)
        target_uint8 = np.array(target_pil, dtype=np.uint8)
        target_float = target_uint8.astype(np.float32).transpose(
            [2, 0, 1]) * (2 / 255) - 1

        proj = Projector()
        proj.set_network(Gs)
        proj.start([target_float])
        proj.dlatents

        dlatents = proj.dlatents  #np.load(dlatents_npz)['dlatents']
        assert dlatents.shape[1:] == (18, 512)  # [N, 18, 512]
        imgs = Gs.components.synthesis.run(
            dlatents,
            output_transform=dict(func=tflib.convert_images_to_uint8,
                                  nchw_to_nhwc=True))
        for i, img in enumerate(imgs):
            #fname = f'{outdir}/dlatent{i:02d}.png'
            #print (f'Saved {fname}')
            return PIL.Image.fromarray(img, 'RGB')  #.save(fname)

    # Render images for dlatents initialized from random seeds.
    Gs_kwargs = {
        'output_transform':
        dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True),
        'randomize_noise':
        False
    }
    # if truncation_psi is not None:
    #     Gs_kwargs['truncation_psi'] = truncation_psi

    noise_vars = [
        var for name, var in Gs.components.synthesis.vars.items()
        if name.startswith('noise')
    ]
    label = np.zeros([1] + Gs.input_shapes[1][1:])
    # if class_idx is not None:
    #     label[:, class_idx] = 1

    # for seed_idx, seed in enumerate(seeds):
    # print('Generating image for seed %d (%d/%d) ...' % (seed, seed_idx, len(seeds)))
    seed = np.random.randint(0, 1000)
    rnd = np.random.RandomState(seed)
    z = rnd.randn(1, *Gs.input_shape[1:])  # [minibatch, component]
    tflib.set_vars(
        {var: rnd.randn(*var.shape.as_list())
         for var in noise_vars})  # [height, width]
    images = Gs.run(z, label,
                    **Gs_kwargs)  # [minibatch, height, width, channel]
    return PIL.Image.fromarray(images[0],
                               'RGB')  #.save(f'{outdir}/seed{seed:04d}.png')
コード例 #23
0
class ViTNet(nn.Module):
    def __init__(self,
                 num_classes=1,
                 dim=32,
                 num_tokens=8,
                 token_c=32,
                 mlp_dim=128,
                 heads=8,
                 depth=2,
                 dropout=0.1):
        super(ViTNet, self).__init__()

        self.conv1 = Conv3d(1,
                            16,
                            kernel_size=3,
                            stride=1,
                            bias=False,
                            padding=1)
        self.conv2 = Conv3d(16,
                            dim,
                            kernel_size=3,
                            stride=1,
                            bias=False,
                            padding=1)
        self.bn1 = BatchNorm3d(16)
        self.bn2 = BatchNorm3d(dim)
        self.pool1 = MaxPool3d(2)
        self.pool2 = MaxPool3d(2)
        self.apply(_weights_init)  # 權重初始化

        # Tokenization
        self.token_wA = Linear(dim, num_tokens)  # Tokenization parameters
        torch.nn.init.xavier_uniform_(self.token_wA.weight)
        self.mat = einsum('bij,bjk->bik')
        self.token_wV = Linear(dim, token_c)  # Tokenization parameters
        torch.nn.init.xavier_uniform_(self.token_wV.weight)

        self.transformer = Transformer(token_c, depth, heads, mlp_dim, dropout)
        self.to_cls_token = nn.Identity()
        self.projector = Projector(in_channels=dim,
                                   out_channels=16,
                                   token_channels=token_c)

        # output
        self.nn1 = Linear(16 * 16 * 16 * 16, 2048)
        self.act1 = ReLU()
        torch.nn.init.xavier_uniform_(self.nn1.weight)
        torch.nn.init.normal_(self.nn1.bias, std=1e-6)
        self.do1 = Dropout(dropout)
        self.nn2 = Linear(2048, 128)
        self.act2 = ReLU()
        torch.nn.init.xavier_uniform_(self.nn2.weight)
        torch.nn.init.normal_(self.nn2.bias, std=1e-6)
        self.nn3 = Linear(128, num_classes)
        torch.nn.init.xavier_uniform_(self.nn3.weight)
        torch.nn.init.normal_(self.nn3.bias, std=1e-6)

    def forward(self, x):
        x = F.relu(self.bn1(self.conv1(x)))
        x = self.pool1(x)
        x = F.relu(self.bn2(self.conv2(x)))
        x = self.pool2(x)
        x = rearrange(x, 'b c d h w -> b (d h w) c')

        # Tokenization
        A = self.token_wA(x)
        A = rearrange(A, 'b h w -> b w h')
        A = A.softmax(dim=-1)
        T = self.mat([A, x])
        T = self.token_wV(T)

        T = self.transformer(T)
        x = self.projector(x, T)
        x = rearrange(x, 'b s c -> b (s c)')
        x = self.act1(self.nn1(x))
        x = self.do1(x)
        x = self.act2(self.nn2(x))
        x = self.nn3(x)
        return x

    def relprop(self,
                cam=None,
                method="transformer_attribution",
                mode=0,
                start_layer=0,
                **kwargs):
        cam = self.nn3.relprop(cam, **kwargs)
        cam = self.act2.relprop(cam, **kwargs)
        cam = self.nn2.relprop(cam, **kwargs)
        cam = self.act1.relprop(cam, **kwargs)
        cam = self.nn1.relprop(cam, **kwargs)
        cam = cam.reshape(1, 4096, 16)
        cam = self.projector.relprop(cam, mode, **kwargs)
        cam = self.transformer.relprop(cam, **kwargs)
        cam = self.token_wV.relprop(cam, **kwargs)
        (cam1, cam2) = self.mat.relprop(cam, **kwargs)
        if mode == 0:
            cam = cam1.transpose(1, 2)
            cam = self.token_wA.relprop(cam, **kwargs)
        else:
            cam = cam2
        cam = rearrange(cam, 'b (d h w) c -> b c d h w', d=16, h=16, w=16)
        cam = self.pool2.relprop(cam, **kwargs)
        cam = self.bn2.relprop(cam, **kwargs)
        cam = self.conv2.relprop(cam, **kwargs)
        cam = self.pool1.relprop(cam, **kwargs)
        cam = self.bn1.relprop(cam, **kwargs)
        cam = self.conv1.relprop(cam, **kwargs)
        return cam
コード例 #24
0
    def paintEventImplementation(self, ev):
        self.selected_item = None
        self.scene = QGraphicsScene()
        self.painter.setRenderHints(QPainter.Antialiasing)

        proj = Projector()
        proj.set_yaw(deg(self.shemetype.zrot.get()))
        proj.set_pitch(-deg(self.shemetype.xrot.get()))
        proj.set_zmul(self.shemetype.zmul.get())
        proj.set_iso_projection(not self.shemetype.axonom.get())
        self.proj = proj

        rebro = self.shemetype.rebro.get()

        br = QColor(0, 0, 0)
        br.setAlphaF(0)
        p = QPen()
        p.setColor(br)

        if self.selected_label_id:
            for label_id, item in self.label_items.items():
                if self.selected_label_id == label_id:
                    green70 = QColor(0, 255, 0)
                    green70.setAlphaF(0.7)
                    self.scene.addRect(item.boundingRect(), brush=green70)

        # Рисуем линии.
        for s in self.shemetype.task["sections"]:
            self.scene.addLine(QLineF(
                proj(s.ax, s.ay, s.az) * rebro,
                proj(s.bx, s.by, s.bz) * rebro,
            ),
                               pen=self.pen)
            self.draw_distrib_forces(s)

        # Кружки нодов.
        for n in self.shemetype.task["nodes"]:  #
            self.draw_sharn(n)
            self.draw_forces(n)
            self.draw_torques(n)

        self.label_items = {}
        # Тексты
        for s in self.shemetype.task["labels"]:
            self.draw_text(paintool.greek(s.text), s.pos, label=s)

        #Сечение

        #section_width = sections.draw_section_routine(
        #	self,
        #	hcenter=0,
        #	right=fini_width)
        rect = self.scene.itemsBoundingRect()
        sectitem = SectionItem(self)
        sectitem.setPos(rect.x() + rect.width(),
                        rect.y() + rect.height() * (4 / 8))
        self.scene.addItem(sectitem)

        # Отрисовка при наведении.
        if self.hovered_node:
            h = self.hovered_node
            pnt = self.proj(h.x, h.y, h.z) * rebro
            self.scene.addEllipse(QRectF(pnt + QPointF(-3, -3),
                                         pnt + QPointF(3, 3)),
                                  pen=self.green,
                                  brush=Qt.green)

            if self.mouse_pressed:
                self.pressed_nodes = []

                def do(a, b, pen, force=False):
                    if force or not self.has_section(self.point(a),
                                                     self.point(b)):
                        self.draw_point(b, pen)
                        self.draw_line(a, b, pen)
                        self.pressed_nodes.append(self.point(b[0], b[1], b[2]))

                do((h.x, h.y, h.z), (h.x + 1, h.y, h.z), self.green)
                do((h.x, h.y, h.z), (h.x - 1, h.y, h.z), self.green)
                do((h.x, h.y, h.z), (h.x, h.y + 1, h.z), self.green)
                do((h.x, h.y, h.z), (h.x, h.y - 1, h.z), self.green)
                do((h.x, h.y, h.z), (h.x, h.y, h.z + 1), self.green)
                do((h.x, h.y, h.z), (h.x, h.y, h.z - 1), self.green)

                if self.hovered_node_pressed is not None:
                    do((h.x, h.y, h.z),
                       self.hovered_node_pressed,
                       self.blue,
                       force=True)

        if self.hovered_sect:
            s = self.hovered_sect
            self.scene.addLine(QLineF(
                self.proj(s.ax, s.ay, s.az) * rebro,
                self.proj(s.bx, s.by, s.bz) * rebro,
            ),
                               pen=self.blue)

        WBORDER = self.shemetype.wborder.get()
        HBORDER = self.shemetype.hborder.get()

        if len(self.shemetype.task["sections"]) == 0:
            self.scene.addRect(QRectF(QPointF(-20, -20), QPointF(20, 20)),
                               brush=br,
                               pen=p)

        rect = self.scene.itemsBoundingRect()
        addtext = paintool.greek(self.shemetype.texteditor.toPlainText())
        n = len(addtext.splitlines())
        for i, l in enumerate(addtext.splitlines()):
            t = self.scene.addText(l, self.font)
            t.setPos(
                rect.x(),
                rect.height() + rect.y() +
                QFontMetrics(self.font).height() * i)

        rect = self.scene.itemsBoundingRect()

        self.scene.addRect(QRectF(rect.x() - WBORDER,
                                  rect.y() - HBORDER,
                                  rect.width() + WBORDER * 2,
                                  rect.height() + HBORDER * 2),
                           pen=p,
                           brush=br)
        self.offset = QPointF(rect.x() - WBORDER, rect.y() - HBORDER)
        self.scene.render(self.painter)

        self.resize_after_render(*self.scene_bound())
コード例 #25
0
from projector import Projector, gray_block
from process_proxy import make_proxy
import time

#print(gray_block(3).astype(int))
#exit(0)

for i in range(1):
    print("Instantiating projector")
    projector = Projector()
    print("Making proxy")
    p = make_proxy(projector)
    print("Deleting original projector")
    del projector
    print("Displaying projector")
    p.show()
    print("Projector displayed")
    print("Getting monitor")
    print("Monitor: " + str(p.get_monitor()))
    print("Waiting...")
    time.sleep(1)
    print("Cycling column gray codes...")
    for b in range(p.get_gray_bits_width()):
        p.show_gray_cols(b)
        time.sleep(0.2)
    print("Cycling row gray codes...")
    for b in range(p.get_gray_bits_height()):
        p.show_gray_rows(b)
        time.sleep(0.2)
    print("Stopping projector")
    p.stop()
コード例 #26
0
ファイル: builder.py プロジェクト: iamyellow/clti
def main(args):
	global script_ok
	argc = len(args)

	start_time = time.time()
	command = args[1].decode("utf-8")
	ensure_dev_path()

	target = 'Debug'
	deploytype = 'development'
	devicefamily = 'iphone'
	debug = False
	build_only = False
	simulator = False
	xcode_build = False
	force_xcode = False
	simtype = devicefamily

	# the run command is when you run from titanium using the run command
	# and it will run the project in the current directory immediately in the simulator
	# from the command line
	if command == 'run':
		project_dir = os.path.expanduser(dequote(args[2].decode("utf-8")))
		iphone_version = dequote(args[3].decode("utf-8"))
		iphone_dir = os.path.abspath(os.path.join(project_dir,'build','iphone'))
		tiapp_xml = os.path.join(project_dir,'tiapp.xml')
		ti = TiAppXML(tiapp_xml)
		appid = ti.properties['id']
		name = ti.properties['name']
		command = 'simulator' # switch it so that the rest of the stuff works
	else:
		iphone_version = dequote(args[2].decode("utf-8"))
		project_dir = os.path.expanduser(dequote(args[3].decode("utf-8")))
		appid = dequote(args[4].decode("utf-8"))
		name = dequote(args[5].decode("utf-8"))
		tiapp_xml = os.path.join(project_dir,'tiapp.xml')
		ti = TiAppXML(tiapp_xml)
		
	app_name = make_app_name(name)
	iphone_dir = os.path.abspath(os.path.join(project_dir,'build','iphone'))
	
	# We need to create the iphone dir if necessary, now that
	# the tiapp.xml allows build target selection
	if not os.path.isdir(iphone_dir):
		if os.path.exists(iphone_dir):
			os.remove(iphone_dir)
		os.makedirs(iphone_dir)
	
	project_xcconfig = os.path.join(iphone_dir,'project.xcconfig')
	target = 'Release'
	ostype = 'os'
	version_file = None
	log_id = None
	provisioning_profile = None
	debughost = None
	debugport = None
	postbuild_modules = []
	
	# starting in 1.4, you don't need to actually keep the build/iphone directory
	# if we don't find it, we'll just simply re-generate it
	if not os.path.exists(iphone_dir):
		from iphone import IPhone
		print "[INFO] Detected missing project but that's OK. re-creating it..."
		iphone_creator = IPhone(name,appid)
		iphone_creator.create(iphone_dir,True)
		sys.stdout.flush()
		
	# we use different arguments dependent on the command
	# pluck those out here
	if command == 'distribute':
		iphone_version = check_iphone_sdk(iphone_version)
		link_version = iphone_version
		dist_keychain = None
		appuuid = dequote(args[6].decode("utf-8"))
		dist_name = dequote(args[7].decode("utf-8"))
		devicefamily = dequote(args[8].decode("utf-8"))
		print "[INFO] Switching to production mode for distribution"
		deploytype = 'production'
	elif command in ['simulator', 'build']:
		link_version = check_iphone_sdk(iphone_version)
		deploytype = 'development'
		debug = True
		simulator = command == 'simulator'
		build_only = command == 'build'
		target = 'Debug'
		ostype = 'simulator'
		devicefamily = dequote(args[4].decode("utf-8"))
		simtype = devicefamily

	elif command in ['install', 'adhoc']:
		iphone_version = check_iphone_sdk(iphone_version)
		devicefamily = dequote(args[6].decode("utf-8"))
		link_version = iphone_version
		dist_keychain = None
		if command == 'install':
			target = 'Debug'
			deploytype = 'test'
		elif command == 'adhoc':
			target = 'Release'
			deploytype = 'production'
	

	# setup up the useful directories we need in the script
	build_out_dir = os.path.abspath(os.path.join(iphone_dir,'build'))
	build_dir = os.path.abspath(os.path.join(build_out_dir,'%s-iphone%s'%(target,ostype)))
	app_dir = os.path.abspath(os.path.join(build_dir,name+'.app'))
	binary = os.path.join(app_dir,name)
	sdk_version = os.path.basename(os.path.abspath(os.path.join(template_dir,'../')))
	iphone_resources_dir = os.path.join(iphone_dir,'Resources')
	version_file = os.path.join(iphone_resources_dir,'.version')
	force_rebuild = read_project_version(project_xcconfig)!=sdk_version or not os.path.exists(version_file)
	infoplist = os.path.join(iphone_dir,'Info.plist')
	githash = None
	custom_fonts = []

	# if we're not running in the simulator we want to clean out the build directory
	if command!='simulator' and os.path.exists(build_out_dir):
		shutil.rmtree(build_out_dir)
	if not os.path.exists(build_out_dir): 
		os.makedirs(build_out_dir)
	# write out the build log, useful for debugging
	o = codecs.open(os.path.join(build_out_dir,'build.log'),'w',encoding='utf-8')
	def log(msg):
		print msg
		o.write(msg)
	try:
		buildtime = datetime.datetime.now()
		o.write("%s\n" % ("="*80))
		o.write("Appcelerator Titanium Diagnostics Build Log\n")
		o.write("The contents of this file are useful to send to Appcelerator Support if\n")
		o.write("reporting an issue to help us understand your environment, build settings\n")
		o.write("and aid in debugging. Please attach this log to any issue that you report.\n")
		o.write("%s\n\n" % ("="*80))
		o.write("Starting build at %s\n\n" % buildtime.strftime("%m/%d/%y %H:%M"))
		
		# write out the build versions info
		versions_txt = read_config(os.path.join(template_dir,'..','version.txt'))
		o.write("Build details:\n\n")
		for key in versions_txt:
			o.write("   %s=%s\n" % (key,versions_txt[key]))
		o.write("\n\n")
		
		if versions_txt.has_key('githash'): 
			githash = versions_txt['githash']
			
		o.write("Script arguments:\n")
		for arg in args:
			o.write(unicode("   %s\n" % arg, 'utf-8'))
		o.write("\n")
		o.write("Building from: %s\n" % template_dir)
		o.write("Platform: %s\n\n" % platform.version())

		# print out path to debug
		xcode_path=run.run(["/usr/bin/xcode-select","-print-path"],True,False)
		if xcode_path:
			o.write("Xcode path is: %s\n" % xcode_path)
		else:
			o.write("Xcode path undetermined\n")

		# find the module directory relative to the root of the SDK	
		titanium_dir = os.path.abspath(os.path.join(template_dir,'..','..','..','..'))
		tp_module_dir = os.path.abspath(os.path.join(titanium_dir,'modules','iphone'))
		force_destroy_build = command!='simulator'

		detector = ModuleDetector(project_dir)
		missing_modules, modules = detector.find_app_modules(ti, 'iphone')
		module_lib_search_path, module_asset_dirs = locate_modules(modules, project_dir, app_dir, log)
		common_js_modules = []
		
		if len(missing_modules) != 0:
			print '[ERROR] Could not find the following required iOS modules:'
			for module in missing_modules:
				print "[ERROR]\tid: %s\tversion: %s" % (module['id'], module['version'])
			exit(1)

		# search for modules that the project is using
		# and make sure we add them to the compile
		for module in modules:
			if module.js:
				common_js_modules.append(module)
				continue
			module_id = module.manifest.moduleid.lower()
			module_version = module.manifest.version
			module_lib_name = ('lib%s.a' % module_id).lower()
			# check first in the local project
			local_module_lib = os.path.join(project_dir, 'modules', 'iphone', module_lib_name)
			local = False
			if os.path.exists(local_module_lib):
				module_lib_search_path.append([module_lib_name, local_module_lib])
				local = True
				log("[INFO] Detected third-party module: %s" % (local_module_lib))
			else:
				if module.lib is None:
					module_lib_path = module.get_resource(module_lib_name)
					log("[ERROR] Third-party module: %s/%s missing library at %s" % (module_id, module_version, module_lib_path))
					sys.exit(1)
				module_lib_search_path.append([module_lib_name, os.path.abspath(module.lib).rsplit('/',1)[0]])
				log("[INFO] Detected third-party module: %s/%s" % (module_id, module_version))
			force_xcode = True

			if not local:
				# copy module resources
				img_dir = module.get_resource('assets', 'images')
				if os.path.exists(img_dir):
					dest_img_dir = os.path.join(app_dir, 'modules', module_id, 'images')
					if not os.path.exists(dest_img_dir):
						os.makedirs(dest_img_dir)
					module_asset_dirs.append([img_dir, dest_img_dir])

				# copy in any module assets
				module_assets_dir = module.get_resource('assets')
				if os.path.exists(module_assets_dir): 
					module_dir = os.path.join(app_dir, 'modules', module_id)
					module_asset_dirs.append([module_assets_dir, module_dir])

		full_version = sdk_version
		if 'version' in versions_txt:
			full_version = versions_txt['version']
			if 'timestamp' in versions_txt or 'githash' in versions_txt:
				full_version += ' ('
				if 'timestamp' in versions_txt:
					full_version += '%s' % versions_txt['timestamp']
				if 'githash' in versions_txt:
					full_version += ' %s' % versions_txt['githash']
				full_version += ')'

		print "[INFO] Titanium SDK version: %s" % full_version
		print "[INFO] iPhone Device family: %s" % devicefamily
		print "[INFO] iPhone SDK version: %s" % iphone_version
		
		if simulator or build_only:
			print "[INFO] iPhone simulated device: %s" % simtype
			# during simulator we need to copy in standard built-in module files
			# since we might not run the compiler on subsequent launches
			for module_name in ('facebook','ui'):
				img_dir = os.path.join(template_dir,'modules',module_name,'images')
				dest_img_dir = os.path.join(app_dir,'modules',module_name,'images')
				if not os.path.exists(dest_img_dir):
					os.makedirs(dest_img_dir)
				module_asset_dirs.append([img_dir,dest_img_dir])

			# when in simulator since we point to the resources directory, we need
			# to explicitly copy over any files
			ird = os.path.join(project_dir,'Resources','iphone')
			if os.path.exists(ird): 
				module_asset_dirs.append([ird,app_dir])
				
			# We also need to copy over the contents of 'platform/iphone'
			platform_iphone = os.path.join(project_dir,'platform','iphone')
			if os.path.exists(platform_iphone):
				module_asset_dirs.append([platform_iphone,app_dir])
			
			for ext in ('ttf','otf'):
				for f in glob.glob('%s/*.%s' % (os.path.join(project_dir,'Resources'),ext)):
					custom_fonts.append(f)
				

		if (command != 'adhoc' and command != 'install'):
			if not (simulator or build_only):
				version = ti.properties['version']
				# we want to make sure in debug mode the version always changes
				version = "%s.%d" % (version,time.time())
				if (deploytype != 'production'):
					ti.properties['version']=version			
					pp = os.path.expanduser("~/Library/MobileDevice/Provisioning Profiles/%s.mobileprovision" % appuuid)
					provisioning_profile = read_provisioning_profile(pp,o)

			create_info_plist(ti, template_dir, project_dir, infoplist)

		applogo = None
		clean_build = False

		# check to see if the appid is different (or not specified) - we need to re-generate
		if read_project_appid(project_xcconfig)!=appid or not infoplist_has_appid(infoplist,appid):
			clean_build = True
			force_xcode = True


		new_lib_hash = None
		lib_hash = None	
		existing_git_hash = None

		# this code simply tries and detect if we're building a different
		# version of the project (or same version but built from different git hash)
		# and if so, make sure we force rebuild so to propagate any code changes in
		# source code (either upgrade or downgrade)
		if os.path.exists(app_dir):
			if os.path.exists(version_file):
				line = open(version_file).read().strip()
				lines = line.split(",")
				v = lines[0]
				log_id = lines[1]
				if len(lines) > 2:
					lib_hash = lines[2]
					existing_git_hash = lines[3]
				if lib_hash==None:
					force_rebuild = True
				else:
					if template_dir==v and force_rebuild==False:
						force_rebuild = False
					else:
						log_id = None
			else:
				force_rebuild = True

		else:
			force_rebuild = True

		o.write("\ngithash=%s, existing_git_hash=%s\n" %(githash,existing_git_hash))
			
		if githash!=existing_git_hash:
			force_rebuild = True

		# we want to read the md5 of the libTiCore.a library since it must match
		# the current one we're building and if not, we need to force a rebuild since
		# that means we've copied in a different version of the library and we need
		# to rebuild clean to avoid linking errors
		source_lib=os.path.join(template_dir,'libTiCore.a')
		fd = open(source_lib,'rb')
		m = hashlib.md5()
		m.update(fd.read(1024)) # just read 1K, it's binary
		new_lib_hash = m.hexdigest()
		fd.close()
		
		if new_lib_hash!=lib_hash:
			force_rebuild=True
			o.write("forcing rebuild since libhash (%s) not matching (%s)\n" % (lib_hash,new_lib_hash))

		lib_hash=new_lib_hash

		# when we force rebuild, we need to re-compile and re-copy source, libs etc
		if force_rebuild:
			o.write("Performing full rebuild\n")
			print "[INFO] Performing full rebuild. This will take a little bit. Hold tight..."
			sys.stdout.flush()
			project = Projector(name,sdk_version,template_dir,project_dir,appid)
			project.create(template_dir,iphone_dir)	
			force_xcode = True
			if os.path.exists(app_dir): shutil.rmtree(app_dir)
			# we have to re-copy if we have a custom version
			create_info_plist(ti, template_dir, project_dir, infoplist)
			# since compiler will generate the module dependencies, we need to 
			# attempt to compile to get it correct for the first time.
			compiler = Compiler(project_dir,appid,name,deploytype)
			compiler.compileProject(xcode_build,devicefamily,iphone_version,True)
		else:
			if simulator:
				softlink_for_simulator(project_dir,app_dir)
			contents="TI_VERSION=%s\n"% sdk_version
			contents+="TI_SDK_DIR=%s\n" % template_dir.replace(sdk_version,'$(TI_VERSION)')
			contents+="TI_APPID=%s\n" % appid
			contents+="OTHER_LDFLAGS[sdk=iphoneos*]=$(inherited) -weak_framework iAd\n"
			contents+="OTHER_LDFLAGS[sdk=iphonesimulator*]=$(inherited) -weak_framework iAd\n"
			contents+="#include \"module\"\n"
			xcconfig = open(project_xcconfig,'w+')
			xccontents = xcconfig.read()
			if contents!=xccontents:
				o.write("writing contents of %s:\n\n%s\n" % (project_xcconfig,contents))
				o.write("old contents\n\n%s\n" % (xccontents))
				xcconfig.write(contents)
				xcconfig.close()
			else:
				o.write("Skipping writing contents of xcconfig %s\n" % project_xcconfig)

		# write out any modules into the xcode project
		# this must be done after project create above or this will be overriden
		link_modules(module_lib_search_path, name, iphone_dir)

		cwd = os.getcwd()

		# check to see if the symlink exists and that it points to the
		# right version of the library
		libticore = os.path.join(template_dir,'libTiCore.a')
		make_link = True
		symlink = os.path.join(iphone_dir,'lib','libTiCore.a')
		if os.path.islink(symlink):
			path = os.path.realpath(symlink)
			if path.find(sdk_version) > 0:
				make_link = False
		if make_link:
			libdir = os.path.join(iphone_dir,'lib')
			if not os.path.exists(libdir): os.makedirs(libdir)
			os.chdir(libdir)
			# a broken link will not return true on os.path.exists
			# so we need to use brute force
			try:
				os.unlink("libTiCore.a")
			except:
				pass
			try:
				os.symlink(libticore,"libTiCore.a")
			except:
				pass
			os.chdir(cwd)

		# if the lib doesn't exist, force a rebuild since it's a new build
		if not os.path.exists(os.path.join(iphone_dir,'lib','libtiverify.a')):
			shutil.copy(os.path.join(template_dir,'libtiverify.a'),os.path.join(iphone_dir,'lib','libtiverify.a'))

		if not os.path.exists(os.path.join(iphone_dir,'lib','libti_ios_debugger.a')):
			shutil.copy(os.path.join(template_dir,'libti_ios_debugger.a'),os.path.join(iphone_dir,'lib','libti_ios_debugger.a'))

		# compile JSS files
		cssc = csscompiler.CSSCompiler(os.path.join(project_dir,'Resources'),devicefamily,appid)
		app_stylesheet = os.path.join(iphone_dir,'Resources','stylesheet.plist')
		asf = codecs.open(app_stylesheet,'w','utf-8')
		asf.write(cssc.code)
		asf.close()

		# compile debugger file
		debug_plist = os.path.join(iphone_dir,'Resources','debugger.plist')
		
		# Force an xcodebuild if the debugger.plist has changed
		force_xcode = write_debugger_plist(debughost, debugport, template_dir, debug_plist)

		if command not in ['simulator', 'build']:
			# compile plist into binary format so it's faster to load
			# we can be slow on simulator
			os.system("/usr/bin/plutil -convert binary1 \"%s\"" % app_stylesheet)
		
		o.write("Generated the following stylecode code:\n\n")
		o.write(cssc.code)
		o.write("\n")

		# generate the Info.plist file with the appropriate device family
		if devicefamily!=None:
			applogo = ti.generate_infoplist(infoplist,appid,devicefamily,project_dir,iphone_version)
		else:
			applogo = ti.generate_infoplist(infoplist,appid,'iphone',project_dir,iphone_version)
			
		# attempt to load any compiler plugins
		if len(ti.properties['plugins']) > 0:
			local_compiler_dir = os.path.abspath(os.path.join(project_dir,'plugins'))
			tp_compiler_dir = os.path.abspath(os.path.join(titanium_dir,'plugins'))
			if not os.path.exists(tp_compiler_dir) and not os.path.exists(local_compiler_dir):
				o.write("+ Missing plugins directory at %s\n" % tp_compiler_dir)
				print "[ERROR] Build Failed (Missing plugins directory). Please see output for more details"
				sys.stdout.flush()
				sys.exit(1)
			compiler_config = {
				'platform':'ios',
				'devicefamily':devicefamily,
				'simtype':simtype,
				'tiapp':ti,
				'project_dir':project_dir,
				'titanium_dir':titanium_dir,
				'appid':appid,
				'iphone_version':iphone_version,
				'template_dir':template_dir,
				'project_name':name,
				'command':command,
				'deploytype':deploytype,
				'build_dir':build_dir,
				'app_name':app_name,
				'app_dir':app_dir,
				'iphone_dir':iphone_dir
			}
			for plugin in ti.properties['plugins']:
				local_plugin_file = os.path.join(local_compiler_dir,plugin['name'],'plugin.py')
				plugin_file = os.path.join(tp_compiler_dir,plugin['name'],plugin['version'],'plugin.py')
				if not os.path.exists(local_plugin_file) and not os.path.exists(plugin_file):
					o.write("+ Missing plugin at %s (checked %s also)\n" % (plugin_file,local_plugin_file))
					print "[ERROR] Build Failed (Missing plugin for %s). Please see output for more details" % plugin['name']
					sys.stdout.flush()
					sys.exit(1)
				o.write("+ Detected plugin: %s/%s\n" % (plugin['name'],plugin['version']))
				print "[INFO] Detected compiler plugin: %s/%s" % (plugin['name'],plugin['version'])
				code_path = plugin_file
				if os.path.exists(local_plugin_file):	
					code_path = local_plugin_file
				o.write("+ Loading compiler plugin at %s\n" % code_path)
				compiler_config['plugin']=plugin
				fin = open(code_path, 'rb')
				m = hashlib.md5()
				m.update(open(code_path,'rb').read()) 
				code_hash = m.hexdigest()
				p = imp.load_source(code_hash, code_path, fin)
				module_functions = dict(inspect.getmembers(p, inspect.isfunction))
				if module_functions.has_key('postbuild'):
					print "[DBEUG] Plugin has postbuild"
					o.write("+ Plugin has postbuild")
					postbuild_modules.append((plugin['name'], p))
				p.compile(compiler_config)
				fin.close()
				
		try:		
			os.chdir(iphone_dir)

			# target the requested value if provided; otherwise, target minimum (4.0)
			# or maximum iphone_version

			if 'min-ios-ver' in ti.ios:
				min_ver = ti.ios['min-ios-ver']
				if min_ver < 4.0:
					print "[INFO] Minimum iOS version %s is lower than 4.0: Using 4.0 as minimum" % min_ver
					min_ver = 4.0
				elif min_ver > float(iphone_version):
					print "[INFO] Minimum iOS version %s is greater than %s (iphone_version): Using %s as minimum" % (min_ver, iphone_version, iphone_version)
					min_ver = float(iphone_version)
			else:
				min_ver = 4.0

			print "[INFO] Minimum iOS version: %s" % min_ver
			deploy_target = "IPHONEOS_DEPLOYMENT_TARGET=%s" % min_ver
			device_target = 'TARGETED_DEVICE_FAMILY=1'  # this is non-sensical, but you can't pass empty string
			
			# No armv6 support above 4.3 or with 6.0+ SDK
			if min_ver >= 4.3 or float(iphone_version) >= 6.0:
				valid_archs = 'armv7 i386'
			else:
				valid_archs = 'armv6 armv7 i386'

			# clean means we need to nuke the build 
			if clean_build or force_destroy_build: 
				print "[INFO] Performing clean build"
				o.write("Performing clean build...\n")
				if os.path.exists(app_dir):
					shutil.rmtree(app_dir)

			if not os.path.exists(app_dir): os.makedirs(app_dir)

			# compile localization files
			# Using app_name here will cause the locale to be put in the WRONG bundle!!
			localecompiler.LocaleCompiler(name,project_dir,devicefamily,deploytype).compile()
			
			# copy any module resources
			if len(module_asset_dirs)>0:
				for e in module_asset_dirs:
					copy_module_resources(e[0],e[1],True)

			# copy CommonJS modules
			for module in common_js_modules:
				#module_id = module.manifest.moduleid.lower()
				#module_dir = os.path.join(app_dir, 'modules', module_id)
				#if os.path.exists(module_dir) is False:
				#	os.makedirs(module_dir)
				shutil.copy(module.js, app_dir)
			
			# copy artworks, if appropriate
			if command in ['adhoc', 'install', 'distribute']:
				artworks = ['iTunesArtwork', 'iTunesArtwork@2x']
				for artwork in artworks:
					if os.path.exists(os.path.join(project_dir, artwork)):
						shutil.copy(os.path.join(project_dir, artwork), app_dir)
			
			# copy any custom fonts in (only runs in simulator)
			# since we need to make them live in the bundle in simulator
			if len(custom_fonts)>0:
				for f in custom_fonts:
					font = os.path.basename(f)
					app_font_path = os.path.join(app_dir, font)
					print "[INFO] Detected custom font: %s" % font
					if os.path.exists(app_font_path):
						os.remove(app_font_path)
					try:
						shutil.copy(f,app_dir)
					except shutil.Error, e:
						print "[WARN] Not copying %s: %s" % (font, e)

			# dump out project file info
			if command not in ['simulator', 'build']:
				dump_resources_listing(project_dir,o)
				dump_infoplist(infoplist,o)

			install_logo(ti, applogo, project_dir, template_dir, app_dir)
			install_defaults(project_dir, template_dir, iphone_resources_dir)

			extra_args = None

			recompile = copy_tiapp_properties(project_dir)
			# if the anything changed in the application defaults then we have to force  a xcode build.
			if recompile == True:
				force_xcode = recompile

			if devicefamily!=None:
				# Meet the minimum requirements for ipad when necessary
				if devicefamily == 'ipad' or devicefamily == 'universal':
					device_target="TARGETED_DEVICE_FAMILY=2"
					# NOTE: this is very important to run on device -- i dunno why
					# xcode warns that 3.2 needs only armv7, but if we don't pass in 
					# armv6 we get crashes on device
					extra_args = ["VALID_ARCHS="+valid_archs]
				# Additionally, if we're universal, change the device family target
				if devicefamily == 'universal':
					device_target="TARGETED_DEVICE_FAMILY=1,2"

			kroll_coverage = ""
			if ti.has_app_property("ti.ios.enablecoverage"):
				enable_coverage = ti.to_bool(ti.get_app_property("ti.ios.enablecoverage"))
				if enable_coverage:
					kroll_coverage = "KROLL_COVERAGE=1"

			def execute_xcode(sdk,extras,print_output=True):

				config = name
				if devicefamily=='ipad':
					config = "%s-iPad" % config
				if devicefamily=='universal':
					config = "%s-universal" % config

				# these are the arguments for running a command line xcode build
				args = ["xcodebuild","-target",config,"-configuration",target,"-sdk",sdk]
				if extras!=None and len(extras)>0: 
					args += extras
				args += [deploy_target,device_target]
				if extra_args!=None and len(extra_args)>0:
					args += extra_args

				o.write("Starting Xcode compile with the following arguments:\n\n")
				for arg in args: o.write("    %s\n" % arg)
				o.write("\napp_id = %s\n" % appid)
				o.write("\n\n")
				o.flush()

				if print_output:
					print "[DEBUG] compile checkpoint: %0.2f seconds" % (time.time()-start_time)
					print "[INFO] Executing XCode build..."
					print "[BEGIN_VERBOSE] Executing XCode Compiler  <span>[toggle output]</span>"

				# h/t cbarber for this; occasionally the PCH header info gets out of sync
				# with the PCH file if you do the "wrong thing" and xcode isn't
				# smart enough to pick up these changes (since the PCH file hasn't 'changed').
				run.run(['touch', '%s_Prefix.pch' % ti.properties['name']], debug=False)
				
				print "[INFO] Siently building..."
				sys.stdout.flush()

				output = run.run(args,False,False,o)

				if print_output:
					print output
					print "[END_VERBOSE]"
					sys.stdout.flush()

				# Output already written by run.run
				#o.write(output)

				# check to make sure the user doesn't have a custom build location 
				# configured in Xcode which currently causes issues with titanium
				idx = output.find("TARGET_BUILD_DIR ")
				if idx > 0:
					endidx = output.find("\n",idx)
					if endidx > 0:
						target_build_dir = dequote(output[idx+17:endidx].strip())
						if not os.path.samefile(target_build_dir,build_dir):
							o.write("+ TARGET_BUILD_DIR = %s\n" % target_build_dir)
							print "[ERROR] Your TARGET_BUILD_DIR is incorrectly set. Most likely you have configured in Xcode a customized build location. Titanium does not currently support this configuration."
							print "[ERROR] Expected dir %s, was: %s" % (build_dir,target_build_dir)
							sys.stdout.flush()
							sys.exit(1)

				# look for build error
				if output.find("** BUILD FAILED **")!=-1 or output.find("ld returned 1")!=-1 or output.find("The following build commands failed:")!=-1:
					o.write("+ Detected build failure\n")
					print "[ERROR] Build Failed. Please see output for more details"
					sys.stdout.flush()
					sys.exit(1)

				o.write("+ Looking for application binary at %s\n" % binary)

				# make sure binary exists
				if not os.path.exists(binary):
					o.write("+ Missing application binary at %s\n" % binary)
					print "[ERROR] Build Failed (Missing app at %s). Please see output for more details" % binary
					sys.stdout.flush()
					sys.exit(1)

				# look for a code signing error
				error = re.findall(r'Code Sign error:(.*)',output)
				if len(error) > 0:
					o.write("+ Detected code sign error: %s\n" % error[0])
					print "[ERROR] Code sign error: %s" % error[0].strip()
					sys.stdout.flush()
					sys.exit(1)
				
			def run_postbuild():
				try:
					if postbuild_modules:
						for p in postbuild_modules:
							o.write("Running postbuild %s" % p[0])
							print "[INFO] Running postbuild %s..." % p[0]
							p[1].postbuild()
				except Exception,e:
					o.write("Error in post-build: %s" % e)
					print "[ERROR] Error in post-build: %s" % e
					

			# build the final release distribution
			args = []

			if command not in ['simulator', 'build']:
				if (command != 'adhoc' and command != 'install'):
					# allow the project to have its own custom entitlements
					custom_entitlements = os.path.join(project_dir,"Entitlements.plist")
					entitlements_contents = None
					if os.path.exists(custom_entitlements):
						entitlements_contents = open(custom_entitlements).read()
						o.write("Found custom entitlements: %s\n" % custom_entitlements)
					else:
						# attempt to customize it by reading prov profile
						entitlements_contents = generate_customized_entitlements(provisioning_profile,appid,appuuid,command,o)
					o.write("Generated the following entitlements:\n\n%s\n\n" % entitlements_contents)
					f=open(os.path.join(iphone_resources_dir,'Entitlements.plist'),'w+')
					f.write(entitlements_contents)
					f.close()
					args+=["CODE_SIGN_ENTITLEMENTS=Resources/Entitlements.plist"]

			# only build if force rebuild (different version) or 
			# the app hasn't yet been built initially
			if ti.properties['guid']!=log_id or force_xcode:
				log_id = ti.properties['guid']
				f = open(version_file,'w+')
				f.write("%s,%s,%s,%s" % (template_dir,log_id,lib_hash,githash))
				f.close()

			# both simulator and build require an xcodebuild
			if command in ['simulator', 'build']:
				debugstr = ''
				if debughost:
					debugstr = 'DEBUGGER_ENABLED=1'
				
				if force_rebuild or force_xcode or not os.path.exists(binary):
					execute_xcode("iphonesimulator%s" % link_version,["GCC_PREPROCESSOR_DEFINITIONS=__LOG__ID__=%s DEPLOYTYPE=development TI_DEVELOPMENT=1 DEBUG=1 TI_VERSION=%s %s %s" % (log_id,sdk_version,debugstr,kroll_coverage)],False)
					
				run_postbuild()
				
				o.write("Finishing build\n")

			if command == 'simulator':
				# sometimes the simulator doesn't remove old log files
				# in which case we get our logging jacked - we need to remove
				# them before running the simulator

				cleanup_app_logfiles(ti, log_id, iphone_version)

				script_ok = True
				
			###########################################################################	
			# END OF SIMULATOR COMMAND	
			###########################################################################			
			
			#
			# this command is run for installing an app on device or packaging for adhoc distribution
			#
			elif command in ['install', 'adhoc']:

				debugstr = ''
				if debughost:
					debugstr = 'DEBUGGER_ENABLED=1'
				
				args += ["DEPLOYMENT_POSTPROCESSING=YES"]

				execute_xcode("iphoneos%s" % iphone_version,args,False)
				
				script_ok = True
				
				run_postbuild()
				
			###########################################################################	
			# END OF INSTALL/ADHOC COMMAND	
			###########################################################################	

			#
			# this command is run for packaging an app for distribution
			#
			elif command == 'distribute':

				deploytype = "production"

				args += [
					"GCC_PREPROCESSOR_DEFINITIONS=DEPLOYTYPE=%s TI_PRODUCTION=1" % deploytype,
					"PROVISIONING_PROFILE=%s" % appuuid,
					"CODE_SIGN_IDENTITY=%s" % dist_name,
					"DEPLOYMENT_POSTPROCESSING=YES"
				]

				if dist_keychain is not None:
					args += ["OTHER_CODE_SIGN_FLAGS=--keychain %s" % dist_keychain]
				
				execute_xcode("iphoneos%s" % iphone_version,args,False)

				dev_path = run.run(['xcode-select','-print-path'],True,False).rstrip()
				package_path = os.path.join(dev_path,'Platforms/iPhoneOS.platform/Developer/usr/bin/PackageApplication')

				ipa = os.path.join(project_dir,"%s.ipa" % name)
				if os.path.exists(package_path):
					output = run.run([package_path,app_dir,"-o",ipa],True)

				print "[INFO] IPA file should be at %s" % ipa

				o.write("Finishing build\n")
				script_ok = True
				
				run_postbuild()
コード例 #27
0
from math import cos, sin, radians
from numpy import array
from projector import Projector

alef = radians(19) # elevation angle
bet = radians(45) # horizontal roration angle

# BEGIN
p = Projector(940, 68)
srcVec = array([0, 0, 15])
vector4 = p.project(srcVec, 19, 45)

print 'Operation 4 vector: {0}'.format(vector4)
puk = 1
コード例 #28
0
from letter import Letter
from projector import Projector

l = Letter()
p = Projector(l)
p.animate()
コード例 #29
0
ファイル: builder.py プロジェクト: mhand/titanium_mobile
def main(args):
	argc = len(args)
	if argc == 2 and (args[1]=='--help' or args[1]=='-h'):
		print "%s <command> <version> <project_dir> <appid> <name> [options]" % os.path.basename(args[0])
		print
		print "available commands: "
		print
		print "  install       install the app to itunes for testing on iphone"
		print "  simulator     build and run on the iphone simulator"
		print "  distribute    build final distribution bundle"
		print "  xcode         build from within xcode"
	
		sys.exit(1)

	print "[INFO] One moment, building ..."
	sys.stdout.flush()
	start_time = time.time()
	command = args[1].decode("utf-8")
	
	target = 'Debug'
	deploytype = 'development'
	devicefamily = None
	debug = False
	simulator = False
	xcode_build = False
	force_xcode = False
	
	if command == 'xcode':
		xcode_build = True
		src_root = os.environ['SOURCE_ROOT']
		project_dir = os.path.abspath(os.path.join(src_root,'../','../'))
		name = os.environ['PROJECT_NAME']
		target = os.environ['CONFIGURATION']
		appid = os.environ['TI_APPID']
		arch = os.environ['CURRENT_ARCH']
		sdk_name = os.environ['SDK_NAME']
		iphone_version = sdk_name.replace('iphoneos','').replace('iphonesimulator','')
		# SUPPORTED_DEVICE_FAMILIES 1 or 2 or both
		# TARGETED_DEVICE_FAMILY 1 or 2
		target_device = os.environ['TARGETED_DEVICE_FAMILY']
		if target_device == '1':
			devicefamily = 'iphone'
		elif target_device == '2':
			devicefamily = 'ipad'
		if arch == 'i386': 
			# simulator always indicates simulator
			deploytype = 'development'
		else:
			# if arch!=i386 indicates a build for device
			if target=='Debug':
				# non-simulator + debug build indicates test on device
				deploytype = 'test'
			else:
				# non-simulator + release build indicates package for distribution
				deploytype = 'production' 
		compiler = Compiler(project_dir,appid,name,deploytype,xcode_build,devicefamily,iphone_version)
	else:
		iphone_version = dequote(args[2].decode("utf-8"))
		iphonesim = os.path.abspath(os.path.join(template_dir,'iphonesim'))
		project_dir = os.path.expanduser(dequote(args[3].decode("utf-8")))
		appid = dequote(args[4].decode("utf-8"))
		name = dequote(args[5].decode("utf-8"))
		app_name = make_app_name(name)
		iphone_dir = os.path.abspath(os.path.join(project_dir,'build','iphone'))
		project_xcconfig = os.path.join(iphone_dir,'project.xcconfig')
		tiapp_xml = os.path.join(project_dir,'tiapp.xml')
		ti = TiAppXML(tiapp_xml)
		target = 'Release'
		ostype = 'os'
		version_file = None
		log_id = None
		
		if command == 'distribute':
			appuuid = dequote(args[6].decode("utf-8"))
			dist_name = dequote(args[7].decode("utf-8"))
			output_dir = os.path.expanduser(dequote(args[8].decode("utf-8")))
			if argc > 9:
				devicefamily = dequote(args[9].decode("utf-8"))
			deploytype = 'production'
		elif command == 'simulator':
			deploytype = 'development'
			debug = True
			simulator = True
			target = 'Debug'
			ostype = 'simulator'
			if argc > 6:
				devicefamily = dequote(args[6].decode("utf-8"))
		elif command == 'install':
			appuuid = dequote(args[6].decode("utf-8"))
			dist_name = dequote(args[7].decode("utf-8"))
			if argc > 8:
				devicefamily = dequote(args[8].decode("utf-8"))
			deploytype = 'test'
		
		build_out_dir = os.path.abspath(os.path.join(iphone_dir,'build'))
		build_dir = os.path.abspath(os.path.join(build_out_dir,'%s-iphone%s'%(target,ostype)))
		app_dir = os.path.abspath(os.path.join(build_dir,name+'.app'))
		binary = os.path.join(app_dir,name)
		sdk_version = os.path.basename(os.path.abspath(os.path.join(template_dir,'../')))
		iphone_resources_dir = os.path.join(iphone_dir,'Resources')
		version_file = os.path.join(iphone_resources_dir,'.simulator')
		force_rebuild = read_project_version(project_xcconfig)!=sdk_version or not os.path.exists(version_file)
		infoplist = os.path.join(iphone_dir,'Info.plist')

		# find the module directory relative to the root of the SDK	
		tp_module_dir = os.path.abspath(os.path.join(template_dir,'..','..','..','..','modules','iphone'))
		tp_modules = []
		tp_depends = []
		
		def find_depends(config,depends):
			for line in open(config).readlines():
				if line.find(':')!=-1:
					(token,value)=line.split(':')
					for entry in value.join(','):
						entry = entry.strip()
						try:
							depends.index(entry)
						except:
							depends.append(entry)

		tp_lib_search_path = []
		for module in ti.properties['modules']:
			tp_name = module['name'].lower()
			tp_version = module['version']
			tp_dir = os.path.join(tp_module_dir,tp_name,tp_version)
			if not os.path.exists(tp_dir):
				print "[ERROR] Third-party module: %s/%s detected in tiapp.xml but not found at %s" % (tp_name,tp_version,tp_dir)
				sys.exit(1)
			libname = 'lib%s.a' % tp_name
			tp_module = os.path.join(tp_dir,libname)
			if not os.path.exists(tp_module):
				print "[ERROR] Third-party module: %s/%s missing library at %s" % (tp_name,tp_version,tp_module)
				sys.exit(1)
			tp_config = os.path.join(tp_dir,'manifest')
			if not os.path.exists(tp_config):
				print "[ERROR] Third-party module: %s/%s missing manifest at %s" % (tp_name,tp_version,tp_config)
				sys.exit(1)
			find_depends(tp_config,tp_depends)	
			tp_modules.append(tp_module)
			tp_lib_search_path.append([libname,os.path.abspath(tp_module)])	
			print "[INFO] Detected third-party module: %s/%s" % (tp_name,tp_version)
			force_xcode = True
		
			# copy module resources
			img_dir = os.path.join(tp_dir,'assets','images')
			if os.path.exists(img_dir):
				dest_img_dir = os.path.join(app_dir,'modules',tp_name,'images')
				if not os.path.exists(dest_img_dir):
					os.makedirs(dest_img_dir)
				copy_module_resources(img_dir,dest_img_dir)
		
		print "[INFO] Titanium SDK version: %s" % sdk_version
		print "[INFO] iPhone Device family: %s" % devicefamily
		print "[INFO] iPhone SDK version: %s" % iphone_version
		
		if simulator:
			# during simulator we need to copy in standard built-in module files
			# since we might not run the compiler on subsequent launches
			for module_name in ('facebook','ui'):
				img_dir = os.path.join(template_dir,'modules',module_name,'images')
				dest_img_dir = os.path.join(app_dir,'modules',module_name,'images')
				if not os.path.exists(dest_img_dir):
					os.makedirs(dest_img_dir)
				copy_module_resources(img_dir,dest_img_dir)
			
			# when in simulator since we point to the resources directory, we need
			# to explicitly copy over any files
			ird = os.path.join(project_dir,'Resources','iphone')
			if os.path.exists(ird): copy_module_resources(ird,app_dir)
			
		# copy XIBs	
		shutil.copy(os.path.join(template_dir,'Resources','MainWindow.xib'),iphone_resources_dir)
		shutil.copy(os.path.join(template_dir,'Resources','MainWindow_ipad.xib'),iphone_resources_dir)
		
		if not simulator:
			version = ti.properties['version']
			# we want to make sure in debug mode the version always changes
			version = "%s.%d" % (version,time.time())
			ti.properties['version']=version
		
		applogo = None
		clean_build = False
		
		# check to see if the appid is different (or not specified) - we need to re-generate
		if read_project_appid(project_xcconfig)!=appid or not infoplist_has_appid(infoplist,appid):
			clean_build = True
			force_xcode = True

		
		new_lib_hash = None
		lib_hash = None	

		if os.path.exists(app_dir):
			if os.path.exists(version_file):
				line = open(version_file).read().strip()
				lines = line.split(",")
				v = lines[0]
				log_id = lines[1]
				if len(lines) > 2:
					lib_hash = lines[2]
					if iphone_version!=lines[3]:
						force_rebuild = True
				if lib_hash==None:
					force_rebuild = True
				else:
					if template_dir==v and force_rebuild==False:
						force_rebuild = False
					else:
						log_id = None
			else:
				force_rebuild = True
				
		else:
			force_rebuild = True

		source_lib=os.path.join(template_dir,'libTiCore.a')
		fd = open(source_lib,'rb')
		m = hashlib.md5()
		m.update(fd.read(1024)) # just read 1K, it's binary
		new_lib_hash = m.hexdigest()
		fd.close()
		
		if new_lib_hash!=lib_hash:
			force_rebuild=True
		
		lib_hash=new_lib_hash
					
		if force_rebuild:
			print "[INFO] Performing full rebuild. This will take a little bit. Hold tight..."
			sys.stdout.flush()
			project = Projector(name,sdk_version,template_dir,project_dir,appid)
			project.create(template_dir,iphone_dir)	
			force_xcode = True
			if os.path.exists(build_out_dir): shutil.rmtree(build_out_dir)
		else:
			xcconfig = open(project_xcconfig,'w')
			xcconfig.write("TI_VERSION=%s\n"% sdk_version)
			xcconfig.write("TI_SDK_DIR=%s\n" % template_dir.replace(sdk_version,'$(TI_VERSION)'))
			xcconfig.write("TI_APPID=%s\n" % appid)
			xcconfig.close()
			
		# write out any modules into the xcode project
		# this must be done after project create above or this will be overriden
		if len(tp_lib_search_path)>0:
			proj = PBXProj()
			xcode_proj = os.path.join(iphone_dir,'%s.xcodeproj'%name,'project.pbxproj')
			current_xcode = open(xcode_proj).read()
			for tp in tp_lib_search_path:
				proj.add_static_library(tp[0],tp[1])
			out = proj.parse(xcode_proj)
			# since xcode changes can be destructive, only write as necessary (if changed)
			if current_xcode!=out:
				o = open(xcode_proj,'w')
				o.write(out)
				o.close()

		cwd = os.getcwd()
		
		# check to see if the symlink exists and that it points to the
		# right version of the library
		libticore = os.path.join(template_dir,'libTiCore.a')
		make_link = True
		symlink = os.path.join(iphone_dir,'lib','libTiCore.a')
		if os.path.islink(symlink):
			path = os.path.realpath(symlink)
			if path.find(sdk_version) > 0:
				make_link = False
		if make_link:
			libdir = os.path.join(iphone_dir,'lib')
			if not os.path.exists(libdir): os.makedirs(libdir)
			os.chdir(libdir)
			if os.path.exists("libTiCore.a"): os.unlink("libTiCore.a")
			os.symlink(libticore,"libTiCore.a")
			os.chdir(cwd)
		
		# if the user has a custom.plist, we'll use it instead of copying
		# over on top
		infoplist_tmpl = os.path.join(iphone_dir,'custom.plist')
		# we allow a custom.plist to indicate that we should use it for
		# our template
		if not os.path.exists(infoplist_tmpl):
			infoplist_tmpl = os.path.join(template_dir,'Info.plist')
			plist = open(os.path.join(template_dir,'Info.plist'),'r').read()
			plist = plist.replace('__PROJECT_NAME__',name)
			plist = plist.replace('__PROJECT_ID__',appid)
			pf = open(infoplist_tmpl,'w+')
			pf.write(plist)
			pf.close()
			
		if devicefamily!=None:
			applogo = ti.generate_infoplist(infoplist,infoplist_tmpl,appid,devicefamily)
		else:
			applogo = ti.generate_infoplist(infoplist,infoplist_tmpl,appid,'iphone')

		# copy over the appicon
		if applogo ==None and ti.properties.has_key('icon'):
			applogo = ti.properties['icon']

		try:		
			os.chdir(iphone_dir)
			
			deploy_target = "IPHONEOS_DEPLOYMENT_TARGET=3.1"
			device_target = 'TARGETED_DEVICE_FAMILY=1'  # this is non-sensical, but you can't pass empty string

			# clean means we need to nuke the build 
			if clean_build and os.path.exists(build_out_dir): 
				print "[INFO] Performing clean build"
				shutil.rmtree(build_out_dir)
			
			# write out the build log, useful for debugging
			if not os.path.exists(build_out_dir): os.makedirs(build_out_dir)
			o = open(os.path.join(build_out_dir,'build.log'),'w')

			if not os.path.exists(app_dir): os.makedirs(app_dir)

			# copy Default.png and appicon each time so if they're 
			# changed they'll stick get picked up	
			app_icon_path = os.path.join(project_dir,'Resources','iphone',applogo)
			if not os.path.exists(app_icon_path):
				app_icon_path = os.path.join(project_dir,'Resources',applogo)
			if os.path.exists(app_icon_path):
				shutil.copy(app_icon_path,app_dir)
			defaultpng_path = os.path.join(project_dir,'Resources','iphone','Default.png')
			if not os.path.exists(defaultpng_path):
				defaultpng_path = os.path.join(project_dir,'Resources','Default.png')
			if os.path.exists(defaultpng_path):
				shutil.copy(defaultpng_path,app_dir)

			extra_args = None
			
			if devicefamily!=None:
				if devicefamily == 'ipad':
					device_target="TARGETED_DEVICE_FAMILY=2"
					deploy_target = "IPHONEOS_DEPLOYMENT_TARGET=3.2"
					# NOTE: this is very important to run on device -- i dunno why
					# xcode warns that 3.2 needs only armv7, but if we don't pass in 
					# armv6 we get crashes on device
					extra_args = ["VALID_ARCHS=armv6 armv7 i386"]
			
			def is_adhoc(uuid):
				path = "~/Library/MobileDevice/Provisioning Profiles/%s.mobileprovision" % uuid
				f = os.path.expanduser(path)
				if os.path.exists(f):
					c = codecs.open(f,'r','utf-8','replace').read()
					return c.find("ProvisionedDevices")!=-1
				return False	
	
			def execute_xcode(sdk,extras,print_output=True):
				
				config = name
				if devicefamily=='ipad':
					config = "%s-iPad" % config
					
				args = ["xcodebuild","-target",config,"-configuration",target,"-sdk",sdk]
				args += extras
				args += [deploy_target,device_target]
				if extra_args!=None:
					args += extra_args
				
				o.write("Starting Xcode compile with the following arguments:\n\n")
				for arg in args: o.write("    %s\n" % arg)
				o.write("\napp_id = %s\n" % appid)
				o.write("\n\n")
				o.flush()
				
				if print_output:
					print "[DEBUG] compile checkpoint: %0.2f seconds" % (time.time()-start_time)
					print "[INFO] Executing XCode build..."
					print "[BEGIN_VERBOSE] Executing XCode Compiler  <span>[toggle output]</span>"

				output = run.run(args)
				
				if print_output:
					print output
					print "[END_VERBOSE]"
					sys.stdout.flush()

				o.write(output)
				
				# check to make sure the user doesn't have a custom build location 
				# configured in Xcode which currently causes issues with titanium
				idx = output.find("TARGET_BUILD_DIR ")
				if idx > 0:
					endidx = output.find("\n",idx)
					if endidx > 0:
						target_build_dir = dequote(output[idx+17:endidx].strip())
						if target_build_dir!=build_dir:
							print "[ERROR] Your TARGET_BUILD_DIR is incorrectly set. Most likely you have configured in Xcode a customized build location. Titanium does not currently support this configuration."
							print "[ERROR] Expected dir %s, was: %s" % (build_dir,target_build_dir)
							sys.stdout.flush()
							sys.exit(1)
			
				# look for build error
				if output.find("** BUILD FAILED **")!=-1 or output.find("ld returned 1")!=-1 or output.find("The following build commands failed:")!=-1:
					print "[ERROR] Build Failed. Please see output for more details"
					sys.stdout.flush()
					sys.exit(1)
					
				# make sure binary exists
				if not os.path.exists(binary):
					print "[ERROR] Build Failed (Missing app at %s). Please see output for more details" % binary
					sys.stdout.flush()
					sys.exit(1)
					
				# look for a code signing error
				error = re.findall(r'Code Sign error:(.*)',output)
				if len(error) > 0:
					print "[ERROR] Code sign error: %s" % error[0].strip()
					sys.stdout.flush()
					sys.exit(1)
					
				sys.exit(0)	
		
			if command == 'simulator':
				
				# only build if force rebuild (different version) or 
				# the app hasn't yet been built initially
				if ti.properties['guid']!=log_id or force_xcode:
					log_id = ti.properties['guid']
					f = open(version_file,'w+')
					f.write("%s,%s,%s,%s" % (template_dir,log_id,lib_hash,iphone_version))
					f.close()
				
				if force_rebuild or force_xcode or not os.path.exists(binary):
					shutil.copy(os.path.join(template_dir,'Classes','defines.h'),os.path.join(iphone_dir,'Classes','defines.h'))
					execute_xcode("iphonesimulator%s" % iphone_version,["GCC_PREPROCESSOR_DEFINITIONS=__LOG__ID__=%s DEPLOYTYPE=development DEBUG=1 TI_VERSION=%s" % (log_id,sdk_version)])
				
				# first make sure it's not running
				kill_simulator()
				
				o.close()

				# sometimes the simulator doesn't remove old log files
				# in which case we get our logging jacked - we need to remove
				# them before running the simulator
				def cleanup_app_logfiles():
					print "[DEBUG] finding old log files"
					sys.stdout.flush()
					def find_all_log_files(folder, fname):
						results = []
						for root, dirs, files in os.walk(os.path.expanduser(folder)):
							for file in files:
								if fname==file:
									fullpath = os.path.join(root, file)
									results.append(fullpath)
						return results
					for f in find_all_log_files("~/Library/Application Support/iPhone Simulator",'%s.log' % log_id):
						print "[DEBUG] removing old log file: %s" % f
						sys.stdout.flush()
						os.remove(f)

				cleanup_app_logfiles()

				sim = None

				def handler(signum, frame):
					print "[INFO] Simulator is exiting"
					sys.stdout.flush()
					if not log == None:
						try:
							os.system("kill -2 %s" % str(log.pid))
						except:
							pass
					if not sim == None and signum!=3:
						try:
							os.system("kill -3 %s" % str(sim.pid))
						except:
							pass

					kill_simulator()
					sys.exit(0)

				signal.signal(signal.SIGHUP, handler)
				signal.signal(signal.SIGINT, handler)
				signal.signal(signal.SIGQUIT, handler)
				signal.signal(signal.SIGABRT, handler)
				signal.signal(signal.SIGTERM, handler)

				print "[INFO] Launching application in Simulator"
				
				sys.stdout.flush()
				sys.stderr.flush()
			
				# launch the simulator
				if devicefamily==None:
					sim = subprocess.Popen("\"%s\" launch \"%s\" %s iphone" % (iphonesim,app_dir,iphone_version),shell=True)
				else:
					sim = subprocess.Popen("\"%s\" launch \"%s\" %s %s" % (iphonesim,app_dir,iphone_version,devicefamily),shell=True)

				# activate the simulator window
				ass = os.path.join(template_dir,'iphone_sim_activate.scpt')
				cmd = "osascript \"%s\"" % ass
				os.system(cmd)

				end_time = time.time()-start_time

				print "[INFO] Launched application in Simulator (%0.2f seconds)" % end_time
				sys.stdout.flush()
				sys.stderr.flush()

				# give the simulator a bit to get started and up and running before 
				# starting the logger
				time.sleep(2)

				logger = os.path.realpath(os.path.join(template_dir,'logger.py'))

				# start the logger
				log = subprocess.Popen([
				  	logger,
					str(log_id)+'.log',
					iphone_version
				])	

				os.waitpid(sim.pid,0)

				print "[INFO] Application has exited from Simulator"

				# in this case, the user has exited the simulator itself
				# and not clicked Stop Emulator from within Developer so we kill
				# our tail log process but let simulator keep running

				if not log == None:
					try:
						os.system("kill -2 %s" % str(log.pid))
					except:
						pass

				sys.exit(0)
				
				
			elif command == 'install':

				args = [
					"GCC_PREPROCESSOR_DEFINITIONS='DEPLOYTYPE=test'",
					"PROVISIONING_PROFILE[sdk=iphoneos*]=%s" % appuuid,
					"CODE_SIGN_IDENTITY[sdk=iphoneos*]=iPhone Developer: %s" % dist_name
				]
				execute_xcode("iphoneos%s" % iphone_version,args,False)
				
				print "[INFO] Installing application in iTunes ... one moment"
				sys.stdout.flush()
				
				output = run.run(["/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/PackageApplication",app_dir,"-v"])
				o.write(output)
				
				# for install, launch itunes with the app
				ipa = os.path.join(os.path.dirname(app_dir),"%s.ipa" % name)
				cmd = "open -b com.apple.itunes \"%s\"" % ipa
				os.system(cmd)
				
				# now run our applescript to tell itunes to sync to get
				# the application on the phone
				ass = os.path.join(template_dir,'itunes_sync.scpt')
				cmd = "osascript \"%s\"" % ass
				os.system(cmd)
				
				print "[INFO] iTunes sync initiated"

				o.close()
				sys.stdout.flush()
				sys.exit(0)
				
			elif command == 'distribute':

				# in this case, we have to do different things based on if it's
				# an ad-hoc distribution cert or not - in the case of non-adhoc
				# we don't use the entitlements file but in ad hoc we need to
				adhoc_line = ""
				deploytype = "production_adhoc"
				if not is_adhoc(appuuid):
					adhoc_line="CODE_SIGN_ENTITLEMENTS = Resources/Entitlements.plist"
					deploytype = "production"

				# build the final release distribution
				args = [
					adhoc_line,
					"GCC_PREPROCESSOR_DEFINITIONS='DEPLOYTYPE=%s'" % deploytype,
					"PROVISIONING_PROFILE[sdk=iphoneos*]=%s" % appuuid,
					"CODE_SIGN_IDENTITY[sdk=iphoneos*]=iPhone Distribution: %s" % dist_name
				]
				execute_xcode("iphoneos%s" % iphone_version,args,False)

				# switch to app_bundle for zip
				os.chdir(build_dir)

				outfile = os.path.join(output_dir,"%s.app.zip"%name)
				if os.path.exists(outfile): os.remove(outfile)
				
				# you *must* use ditto here or it won't upload to appstore
				os.system('ditto -ck --keepParent --sequesterRsrc "%s.app" "%s"' % (name,outfile))
				
				sys.exit(0)
				
		finally:
			os.chdir(cwd)
コード例 #30
0
from projector import Projector

my_projector = Projector('wxga', 2000)
my_projector.get_projector_resolution()
コード例 #31
0
def main(args):
    if len(args) < 2:
        print "Usage: %s <project_directory> [sdk_verison]" % os.path.basename(
            args[0])
        sys.exit(1)

    # What needs to be done in order to perform a "true" export?
    # ---
    # Wipe the build dir
    # Migrate resources
    # Migrate tiapp.xml (required for scripts)
    # Generate project from template
    # Populate Info.plist
    # Compile/migrate i18n
    # Migrate scripts for compiling JSS files (and i18n)
    # Modify xcodeproj build steps to call the JSS compiler
    # Then... Share and Enjoy.

    project_dir = os.path.abspath(args[1])
    build_dir = os.path.join(project_dir, 'build', 'iphone')
    titanium_local = os.path.join(build_dir, 'titanium')

    if len(args) == 3:
        version = args[2]
        sdk_dir = find_sdk(version)
    else:
        sdk_dir = os.path.abspath(os.path.dirname(template_dir))
        version = os.path.basename(sdk_dir)

    tiappxml = os.path.join(project_dir, 'tiapp.xml')
    tiapp = TiAppXML(tiappxml)

    app_id = tiapp.properties['id']
    app_name = tiapp.properties['name']

    if app_id is None or app_name is None:
        info("Your tiapp.xml is malformed - please specify an app name and id")
        sys.exit(1)

    # Clean build dir (if it exists), error otherwise (no iphone support)
    info("Cleaning build...")
    if os.path.exists(build_dir):
        for f in os.listdir(build_dir):
            path = os.path.join(build_dir, f)
            if os.path.isfile(path):
                os.remove(path)
            else:
                shutil.rmtree(path)
    else:
        info("Your project is not configured to be built for iphone.")
        exit(1)

    # Migrate Resources
    info("Migrating resources...")
    project_resources = os.path.join(project_dir, 'Resources')
    resources_dir = os.path.join(build_dir, 'Resources')

    shutil.copytree(project_resources, resources_dir)

    # Migrate platform/iphone contents into Resources.
    info("Migrating platform/iphone to Resources...")
    project_platform = os.path.join(project_dir, 'platform', 'iphone')

    if os.path.isdir(project_platform):
        contents = os.listdir(project_platform)
        for file in contents:
            path = os.path.join(project_platform, file)
            if os.path.isdir(path):
                shutil.copytree(path, os.path.join(resources_dir, file))
            else:
                shutil.copy(path, os.path.join(resources_dir, file))

    # Migrate tiapp.xml
    info("Migrating tiapp.xml...")
    shutil.copy(tiappxml, build_dir)

    # Generate project stuff from the template
    info("Generating project from Titanium template...")
    project = Projector(app_name, version, template_dir, project_dir, app_id)
    project.create(template_dir, build_dir)

    # Because the debugger.plist is built as part of the required
    # resources, we need to autogen an empty one
    debug_plist = os.path.join(resources_dir, 'debugger.plist')
    force_xcode = write_debugger_plist(None, None, template_dir, debug_plist)

    # Populate Info.plist
    applogo = None
    info("Populating Info.plist...")
    plist_out = os.path.join(build_dir, 'Info.plist')
    create_info_plist(tiapp, template_dir, project_dir, plist_out)
    applogo = tiapp.generate_infoplist(plist_out, app_id, 'iphone',
                                       project_dir, None)

    # Run the compiler to autogenerate .m files
    info("Copying classes, creating generated .m files...")
    compiler = Compiler(project_dir, app_id, app_name, 'export')
    compiler.compileProject(silent=True)

    #... But we still have to nuke the stuff that gets built that we don't want
    # to bundle.
    ios_build = os.path.join(build_dir, 'build')
    if os.path.isdir(ios_build):
        shutil.rmtree(os.path.join(build_dir, 'build'))

    # Install applogo/splash/etc.
    info("Copying icons and splash...")
    install_logo(tiapp, applogo, project_dir, template_dir, resources_dir)
    install_defaults(project_dir, template_dir, resources_dir)

    # Get Modules
    detector = ModuleDetector(project_dir)
    missing_modules, modules = detector.find_app_modules(tiapp, 'iphone')

    if len(missing_modules) != 0:
        for module in missing_modules:
            info("MISSING MODULE: %s ... Project will not build correctly" %
                 module['id'])
        info("Terminating export: Please fix your modules.")
        sys.exit(1)

    module_search_path, module_asset_dirs = locate_modules(
        modules, project_dir, resources_dir, info)

    lib_dir = os.path.join(build_dir, 'lib')
    if not os.path.exists(lib_dir):
        os.makedirs(lib_dir)

    if len(module_search_path) > 0:
        info("Copying modules...")
        for module in module_search_path:
            module_name, module_path = module
            info("\t%s..." % module_name)
            shutil.copy(os.path.join(module_path, module_name), lib_dir)
            module[1] = os.path.join(lib_dir, module_name)

        info("Copying module metadata...")
        metadata_dir = os.path.join(build_dir, 'metadata')
        for module in modules:
            module_metadata = os.path.join(module.path, 'metadata.json')
            if os.path.exists(module_metadata):
                if not os.path.exists(metadata_dir):
                    os.makedirs(metadata_dir)
                target = os.path.join(metadata_dir,
                                      "%s.json" % module.manifest.moduleid)
                shutil.copyfile(module_metadata, target)

        # Note: The module link information has to be added to
        # the xcodeproj after it's created.
        # We also have to mod the module_search_path to reference
        # the local 'lib' directory instead of the original
        # module install location
        info("Linking modules...")
        local_modules = []
        for module in module_search_path:
            name = module[0]
            newpath = os.path.join('lib', name)
            local_modules.append([name, newpath])
        link_modules(local_modules, app_name, build_dir, relative=True)

    # Copy libraries
    info("Copying libraries...")
    iphone_dir = os.path.join(sdk_dir, 'iphone')
    for lib in glob.iglob(os.path.join(iphone_dir, 'lib*')):
        info("\t%s..." % lib)
        shutil.copy(lib, lib_dir)

    # Process i18n files
    info("Processing i18n...")
    locale_compiler = LocaleCompiler(app_name, project_dir, 'ios',
                                     'development', resources_dir)
    locale_compiler.compile()

    # Migrate compile scripts
    info("Copying custom Titanium compiler scripts...")
    shutil.copytree(os.path.join(sdk_dir, 'common'), titanium_local)
    shutil.copy(os.path.join(sdk_dir, 'tiapp.py'), titanium_local)

    iphone_script_dir = os.path.join(titanium_local, 'iphone')
    os.mkdir(iphone_script_dir)
    shutil.copy(os.path.join(sdk_dir, 'iphone', 'compiler.py'),
                iphone_script_dir)
    shutil.copy(os.path.join(sdk_dir, 'iphone', 'tools.py'), iphone_script_dir)
    shutil.copy(os.path.join(sdk_dir, 'iphone', 'run.py'), iphone_script_dir)
    shutil.copy(os.path.join(sdk_dir, 'iphone', 'csspacker.py'),
                iphone_script_dir)
    shutil.copy(os.path.join(sdk_dir, 'iphone', 'jspacker.py'),
                iphone_script_dir)
    shutil.copy(os.path.join(sdk_dir, 'iphone', 'titanium_prep'),
                iphone_script_dir)

    # Add compilation to the build script in project
    info("Modifying pre-compile stage...")
    xcodeproj = os.path.join(build_dir, '%s.xcodeproj' % app_name,
                             'project.pbxproj')
    contents = codecs.open(xcodeproj, 'r', encoding='utf-8').read()

    css_compiler = os.path.join('titanium', 'css', 'csscompiler.py')
    ti_compiler = os.path.join('titanium', 'iphone', 'compiler.py')
    script = """%s . ios Resources
%s . export-build $TARGETED_DEVICE_FAMILY $SDKROOT %s""" % (
        css_compiler, ti_compiler, version)
    contents = fix_xcode_script(contents, "Pre-Compile", script)

    # write our new project
    f = codecs.open(xcodeproj, 'w', encoding='utf-8')
    f.write(contents)
    f.close()

    info("Finished! Share and Enjoy.")
コード例 #32
0
ファイル: api.py プロジェクト: zim2411/projectorpy
                    level=logging.DEBUG,
                    format='%(asctime)s %(name)s %(levelname)s: %(message)s')
logger = logging.getLogger('api')

# Use environment variable PROJECTOR_SERIAL to configure the port to use
if 'PROJECTOR_SERIAL' in os.environ:
    # this is automatically set to a suitable default in run.sh
    projector_port = os.environ['PROJECTOR_SERIAL']
else:
    # punt - fall back to a common serial port name on some Linux systems
    logger.error('PROJECTOR_SERIAL is not set in the environment')
    projector_port = '/dev/ttyS0'
logger.info('Serial port configured as: %s', projector_port)

# setup our objects
projector = Projector(projector_port)
spec = ProjectorSpec()
app = Flask(__name__)


# custom exceptions
class UnknownCommandError(ValueError):
    pass


class BadParameterError(ValueError):
    pass


class SerialError(ValueError):
    pass
コード例 #33
0
def main(args):
		if len(args) < 2:
				print "Usage: %s <project_directory> [sdk_verison]" % os.path.basename(args[0])
				sys.exit(1)

		# What needs to be done in order to perform a "true" export?
		# ---
		# Wipe the build dir
		# Migrate resources
		# Migrate tiapp.xml (required for scripts)
		# Generate project from template
		# Populate Info.plist
		# Compile/migrate i18n 
		# Migrate scripts for compiling JSS files (and i18n)
		# Modify xcodeproj build steps to call the JSS compiler
		# Then... Share and Enjoy.
		
		project_dir = os.path.abspath(args[1])
		build_dir = os.path.join(project_dir,'build','iphone')
		titanium_local = os.path.join(build_dir,'titanium')
		
		if len(args) == 3:
			version = args[2]
			sdk_dir = find_sdk(version)
		else:
			sdk_dir = os.path.abspath(os.path.dirname(template_dir))
			version = os.path.basename(sdk_dir)			

		tiappxml = os.path.join(project_dir, 'tiapp.xml')
		tiapp = TiAppXML(tiappxml)
		
		app_id = tiapp.properties['id']
		app_name = tiapp.properties['name']
		
		if app_id is None or app_name is None:
			info("Your tiapp.xml is malformed - please specify an app name and id")
			sys.exit(1)
		
		# Clean build dir (if it exists), error otherwise (no iphone support)
		info("Cleaning build...")
		if os.path.exists(build_dir):
			for f in os.listdir(build_dir):
				path = os.path.join(build_dir,f)
				if os.path.isfile(path):
					os.remove(path)
				else:
					shutil.rmtree(path)
		else:
			info("Your project is not configured to be built for iphone.")
			exit(1)
		
		# Migrate Resources
		info("Migrating resources...")
		project_resources = os.path.join(project_dir, 'Resources')
		resources_dir = os.path.join(build_dir, 'Resources')
		
		shutil.copytree(project_resources,resources_dir)

		# Migrate platform/iphone contents into Resources.
		info("Migrating platform/iphone to Resources...")
		project_platform = os.path.join(project_dir,'platform','iphone')
		
		if os.path.isdir(project_platform):
			contents = os.listdir(project_platform)
			for file in contents:
				path = os.path.join(project_platform,file)
				if os.path.isdir(path):
					shutil.copytree(path, os.path.join(resources_dir,file))
				else:
					shutil.copy(path, os.path.join(resources_dir,file))
		
		# Migrate tiapp.xml
		info("Migrating tiapp.xml...")
		shutil.copy(tiappxml, build_dir)
		
		# Generate project stuff from the template
		info("Generating project from Titanium template...")
		project = Projector(app_name,version,template_dir,project_dir,app_id)
		project.create(template_dir,build_dir)			
		
		# Because the debugger.plist is built as part of the required
		# resources, we need to autogen an empty one
		debug_plist = os.path.join(resources_dir,'debugger.plist')
		force_xcode = write_debugger_plist(None, None, template_dir, debug_plist)
		
		# Populate Info.plist
		applogo = None
		info("Populating Info.plist...")
		plist_out = os.path.join(build_dir, 'Info.plist')
		create_info_plist(tiapp, template_dir, project_dir, plist_out)
		applogo = tiapp.generate_infoplist(plist_out, app_id, 'iphone', project_dir, None)
		
		# Run the compiler to autogenerate .m files
		info("Copying classes, creating generated .m files...")
		compiler = Compiler(project_dir,app_id,app_name,'export')
		compiler.compileProject(silent=True)
		
		#... But we still have to nuke the stuff that gets built that we don't want
		# to bundle.
		ios_build = os.path.join(build_dir,'build')
		if os.path.isdir(ios_build):
			shutil.rmtree(os.path.join(build_dir,'build'))
		
		# Install applogo/splash/etc.
		info("Copying icons and splash...")
		install_logo(tiapp, applogo, project_dir, template_dir, resources_dir)
		install_defaults(project_dir, template_dir, resources_dir)
		
		# Get Modules
		detector = ModuleDetector(project_dir)
		missing_modules, modules = detector.find_app_modules(tiapp, 'iphone')
		
		if len(missing_modules) != 0:
			for module in missing_modules:
				info("MISSING MODULE: %s ... Project will not build correctly" % module['id'])
			info("Terminating export: Please fix your modules.")
			sys.exit(1)
		
		module_search_path, module_asset_dirs = locate_modules(modules, project_dir, resources_dir, info)
		
		lib_dir = os.path.join(build_dir, 'lib')
		if not os.path.exists(lib_dir): 
			os.makedirs(lib_dir)
		
		if len(module_search_path) > 0:
			info("Copying modules...")
			for module in module_search_path:
				module_name, module_path = module
				info("\t%s..." % module_name)
				shutil.copy(os.path.join(module_path, module_name), lib_dir)
				module[1] = os.path.join(lib_dir, module_name)
				
			info("Copying module metadata...")
			metadata_dir = os.path.join(build_dir, 'metadata')
			for module in modules:
				module_metadata = os.path.join(module.path,'metadata.json')
				if os.path.exists(module_metadata):
					if not os.path.exists(metadata_dir):
						os.makedirs(metadata_dir)
					target = os.path.join(metadata_dir, "%s.json" % module.manifest.moduleid)
					shutil.copyfile(module_metadata, target)
			
			# Note: The module link information has to be added to
			# the xcodeproj after it's created.
			# We also have to mod the module_search_path to reference
			# the local 'lib' directory instead of the original
			# module install location
			info("Linking modules...")
			local_modules = []
			for module in module_search_path:
				name = module[0]
				newpath = os.path.join('lib',name)
				local_modules.append([name, newpath])
			link_modules(local_modules, app_name, build_dir, relative=True)	
		
		# Copy libraries
		info("Copying libraries...")
		iphone_dir = os.path.join(sdk_dir, 'iphone')
		for lib in glob.iglob(os.path.join(iphone_dir,'lib*')):
			info("\t%s..." % lib)
			shutil.copy(lib, lib_dir)
		
		# Process i18n files
		info("Processing i18n...")
		locale_compiler = LocaleCompiler(app_name, project_dir, 'ios', 'development', resources_dir)
		locale_compiler.compile()
		
		# Migrate compile scripts
		info("Copying custom Titanium compiler scripts...")
		shutil.copytree(os.path.join(sdk_dir,'common'),titanium_local)
		shutil.copy(os.path.join(sdk_dir,'tiapp.py'),titanium_local)
		
		iphone_script_dir = os.path.join(titanium_local,'iphone')
		os.mkdir(iphone_script_dir)
		shutil.copy(os.path.join(sdk_dir,'iphone','compiler.py'),iphone_script_dir)
		shutil.copy(os.path.join(sdk_dir,'iphone','run.py'),iphone_script_dir)
		shutil.copy(os.path.join(sdk_dir,'iphone','csspacker.py'),iphone_script_dir)
		shutil.copy(os.path.join(sdk_dir,'iphone','jspacker.py'),iphone_script_dir)
		shutil.copy(os.path.join(sdk_dir,'iphone','titanium_prep'),iphone_script_dir)
		
		# Add compilation to the build script in project
		info("Modifying pre-compile stage...")
		xcodeproj = os.path.join(build_dir,'%s.xcodeproj' % app_name, 'project.pbxproj')
		contents = codecs.open(xcodeproj,'r',encoding='utf-8').read()

		css_compiler = os.path.join('titanium','css','csscompiler.py')
		ti_compiler = os.path.join('titanium','iphone','compiler.py')
		script = """%s . ios Resources
%s . export-build $TARGETED_DEVICE_FAMILY $SDKROOT %s""" % (css_compiler, ti_compiler, version)
		contents = fix_xcode_script(contents,"Pre-Compile",script)

		# write our new project
		f = codecs.open(xcodeproj,'w',encoding='utf-8')
		f.write(contents)
		f.close()		
		
		info("Finished! Share and Enjoy.")
コード例 #34
0
ファイル: sbtv-playground.py プロジェクト: ashkarin/ctreco-py
def dfi_evelina_version(useCuda = 0):
    def FP_f (ct_slice, n_angles, angle_step):
        spect = np.fft.fftshift(np.fft.fft2(np.fft.fftshift(ct_slice)))
        if useCuda:
          return ctmasking.getSpectMaskCUDA (n_angles, angle_step, spect)
        else:
          return ctmasking.getSpectMask (n_angles, angle_step, spect)

    def BP_f (measurements, n_angles, angle_step):
        return np.real(np.fft.fftshift(np.fft.ifft2(np.fft.ifftshift(measurements))))

    #sino_path = "sino512.tif" # 1.25 deg, 180 proj
    sino_path = "testdata/forbild512_sino12575.tif" # 180/251 deg, 180 proj
    sino = Image.open(sino_path)
    sino_array = np.array(sino)

    side_size  = sino_array.shape[1]
    n_angles   = sino_array.shape[0]
    angle_step = np.pi / n_angles
    interpolation = 1

    new_rho_len, theta_len, padded_sino = Projector.zeropadding(sino_array, 2)
    print theta_len, n_angles, new_rho_len

    fourier_sino = np.zeros_like(padded_sino, dtype=complex)
    for r in range(np.size(padded_sino, 0)):
        fourier_sino[r,:] = np.fft.fft(padded_sino[r,:])


    projector = None
    if useCuda:
        projector = Projector.CUDA(interpolation);
    else:
        projector = Projector.CPU(interpolation);

    dfi_recon_spect = projector.DFI(fourier_sino, angle_step)

    ## Workaround
    # Reconstruct image
    ct_img = np.fft.fftshift(np.fft.ifft2(np.fft.ifftshift(dfi_recon_spect)))
    # Normalize to [0..255]
    ct_img = mat2gray(ct_img) * 255.0
    plt.imshow(np.real(ct_img), cmap=plt.get_cmap(COLOR_MAP))
    plt.show(1)
    # Get new measurements
    measurements = FP_f (ct_img, n_angles, angle_step)
    ##

    print "DFI done, measurements were obtained"

    u = sbtv.sbtv (measurements = measurements,
                   side_size = new_rho_len,
                   n_angles = n_angles,
                   angle_step = angle_step,
                   max_iter_cgs = 10,
                   max_iter = 3,
                   BP=BP_f,
                   FP=FP_f)

    plt.figure("Reconstruction using DFI+Evelina approach")
    plt.imshow(np.real(u), cmap=plt.get_cmap(COLOR_MAP))
    plt.show(1)