def handle_result(operation, process_id, printer, result, thread):
    #print(thread.process_id)
    #print(thread.params)
    process_region = printer.panel.find(process_id,0)
    status_region = printer.panel.find('Result:',process_region.begin())

    try:
        result = json.loads(result)
        if operation == 'compile' and 'actions' in result and util.to_bool(result['success']) == False:
            diff_merge_settings = config.settings.get('mm_diff_server_conflicts', False)
            if diff_merge_settings:
                if sublime.ok_cancel_dialog(result["body"], result["actions"][0].title()):
                    printer.panel.run_command('write_operation_status', {"text": " Diffing with server", 'region': [status_region.end(), status_region.end()+10] })
                    th = MavensMateDiffThread(thread.window, thread.view, result['tmp_file_path'])
                    th.start()
                    
                else:
                    printer.panel.run_command('write_operation_status', {"text": " "+result["actions"][1].title(), 'region': [status_region.end(), status_region.end()+10] })
            else:
                if sublime.ok_cancel_dialog(result["body"], "Overwrite Server Copy"):
                    printer.panel.run_command('write_operation_status', {"text": " Overwriting server copy", 'region': [status_region.end(), status_region.end()+10] })
                    thread.params['action'] = 'overwrite'
                    sublime.set_timeout(lambda: call('compile', params=thread.params), 100)   
                else:
                    printer.panel.run_command('write_operation_status', {"text": " "+result["actions"][1].title(), 'region': [status_region.end(), status_region.end()+10] })
   
        else:
            print_result_message(operation, process_id, status_region, result, printer, thread) 
            if operation == 'new_metadata' and 'success' in result and util.to_bool(result['success']) == True:
                if 'messages' in result:
                    if type(result['messages']) is not list:
                        result['messages'] = [result['messages']]
                    for m in result['messages']:
                        if 'package.xml' not in m['fileName']:
                            file_name = m['fileName']
                            location = util.mm_project_directory() + "/" + file_name.replace('unpackaged/', 'src/')
                            sublime.active_window().open_file(location)
                            break
            if 'success' in result and util.to_bool(result['success']) == True:
                if printer != None and len(ThreadTracker.get_pending_mm_panel_threads(thread.window)) == 0:
                    printer.hide()  
            elif 'State' in result and result['State'] == 'Completed' and len(ThreadTracker.get_pending_mm_panel_threads(thread.window)) == 0:
                #tooling api
                if printer != None:
                    printer.hide()
            if operation == 'refresh':            
                sublime.set_timeout(lambda: sublime.active_window().active_view().run_command('revert'), 200)
                util.clear_marked_line_numbers()
    except AttributeError:   
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: '+result+'\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: '+result
            printer.panel.run_command('write_operation_status', {'text': msg, 'region': [status_region.end(), status_region.end()+10] })
    except Exception:
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: '+result+'\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: '+result
            printer.panel.run_command('write_operation_status', {'text': msg, 'region': [status_region.end(), status_region.end()+10] })
    def run(self):
        if self.use_mm_panel:
            if sys.version_info >= (3, 0):
                self.calculate_process_region()
            PanelThreadProgress(self)

        #last_thread = ThreadTracker.get_last_added(self.window)
        ThreadTracker.add(self)

        if self.settings.get('mm_debug_mode'):
            python_path = self.settings.get('mm_python_location')
            mm_loc = self.settings.get('mm_debug_location')
            print('[MAVENSMATE] executing DEBUG mm terminal call:')
            print("{0} {1} {2}".format(python_path, pipes.quote(mm_loc), self.get_arguments()))
            process = subprocess.Popen("{0} {1} {2}".format(python_path, pipes.quote(mm_loc), self.get_arguments()), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
        else:
            print('[MAVENSMATE] executing mm terminal call:')
            print("{0} {1}".format(pipes.quote(self.mm_location), self.get_arguments()))
            process = subprocess.Popen("{0} {1}".format(self.mm_location, self.get_arguments()), cwd=sublime.packages_path(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
        self.submit_payload(process)
        if process.stdout is not None: 
            mm_response = process.stdout.readlines()
        elif process.stderr is not None:
            mm_response = process.stderr.readlines()
        try:
            response_body = '\n'.join(mm_response)
        except:
            strs = []
            for line in mm_response:
                strs.append(line.decode('utf-8'))   
            response_body = '\n'.join(strs)

        print('[MAVENSMATE] response from mm: ' + response_body)
        self.result = response_body
        if self.operation == 'compile':
            compile_callback(self, response_body)
        
        #if self.operation == 'new_apex_overlay' or self.operation == 'delete_apex_overlay':
        #    sublime.set_timeout(lambda : index_overlays(self.window), 100)
        
        #if self.callback != None:
        #    print(self.callback)
        #    self.callback(response_body)

        if sys.version_info >= (3, 0):
            self.calculate_process_region()
            
        ThreadTracker.remove(self)
def index_overlays(window):
    pending_threads = ThreadTracker.get_pending(window)
    run_index_thread = True
    for t in pending_threads:
        if t.operation == 'index_apex_overlays':
            run_index_thread = False
            break
    if run_index_thread:
        call('index_apex_overlays', False)
 def hide_callback(self, hide_time, thread):
     if thread:
         last_added = ThreadTracker.get_last_added(self.window_id)
         if thread != last_added:
             return
     if self.visible and self.hide_time and hide_time == self.hide_time:
         if not self.just_error:
             self.window.run_command('hide_panel')
         self.just_error = False
def index_apex_code(window):
    pending_threads = ThreadTracker.get_pending(window)
    run_index_thread = True
    for t in pending_threads:
        if t.operation == 'index_apex':
            run_index_thread = False
            break
    if run_index_thread:
        call('index_apex', False)
 def hide_callback(self, hide_time, thread):
     if thread:
         last_added = ThreadTracker.get_last_added(self.window_id)
         if thread != last_added:
             return
     if self.visible and self.hide_time and hide_time == self.hide_time:
         if not self.just_error:
             self.window.run_command('hide_panel')
         self.just_error = False
def index_apex_code(thread):
    pending_threads = ThreadTracker.get_pending(thread.window)
    run_index_thread = True
    for t in pending_threads:
        if t.operation == 'index_apex':
            run_index_thread = False
            break
    if run_index_thread:
        params = {"files": thread.params.get('files', [])}
        call('index_apex', False, params=params)
def index_apex_code(thread):
    pending_threads = ThreadTracker.get_pending(thread.window)
    run_index_thread = True
    for t in pending_threads:
        if t.operation == 'index_apex':
            run_index_thread = False
            break
    if run_index_thread:
        params = {
            "files" : thread.params.get('files', [])
        }
        call('index_apex', False, params=params)  
    def run(self):
        if self.use_mm_panel:
            if sys.version_info >= (3, 0):
                self.calculate_process_region()
            PanelThreadProgress(self)

        #last_thread = ThreadTracker.get_last_added(self.window)
        ThreadTracker.add(self)

        if self.settings.get('mm_debug_mode') or 'darwin' not in sys.platform:
            python_path = self.settings.get('mm_python_location')
            if 'darwin' in sys.platform or self.settings.get('mm_debug_location') != None:
                mm_loc = self.settings.get('mm_debug_location')
            else:
                mm_loc = os.path.join(config.mm_dir,"mm","mm.py") #mm.py is bundled with sublime text plugin
            
            if 'linux' in sys.platform or 'darwin' in sys.platform:
                #osx, linux
                debug('executing mm terminal call:')
                debug("{0} {1} {2}".format(python_path, pipes.quote(mm_loc), self.get_arguments()))
                process = subprocess.Popen('\'{0}\' \'{1}\' {2}'.format(python_path, mm_loc, self.get_arguments()), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
            else:
                #windows
                if self.settings.get('mm_debug_mode', False):
                    #user wishes to use system python
                    python_path = self.settings.get('mm_python_location')
                    process = subprocess.Popen('"{0}" "{1}" {2}'.format(python_path, mm_loc, self.get_arguments()), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
                else:
                    python_path = os.path.join(os.environ["ProgramFiles"],"MavensMate","App","python.exe")
                    if not os.path.isfile(python_path):
                        python_path = python_path.replace("Program Files", "Program Files (x86)")
                    debug('executing mm terminal call:')
                    debug('"{0}" -E "{1}" {2}'.format(python_path, mm_loc, self.get_arguments()))
                    process = subprocess.Popen('"{0}" -E "{1}" {2}'.format(python_path, mm_loc, self.get_arguments()), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
        else:
            debug('executing mm terminal call:')
            debug("{0} {1}".format(pipes.quote(self.mm_location), self.get_arguments()))
            process = subprocess.Popen("{0} {1}".format(self.mm_location, self.get_arguments()), cwd=sublime.packages_path(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
        self.submit_payload(process)
        if process.stdout is not None: 
            mm_response = process.stdout.readlines()
        elif process.stderr is not None:
            mm_response = process.stderr.readlines()
        try:
            response_body = '\n'.join(mm_response)
        except:
            strs = []
            for line in mm_response:
                strs.append(line.decode('utf-8'))   
            response_body = '\n'.join(strs)

        debug('response from mm: ' + response_body)
        self.result = response_body
        if self.operation == 'compile':
            compile_callback(self, response_body)
        
        #if self.operation == 'new_apex_overlay' or self.operation == 'delete_apex_overlay':
        #    sublime.set_timeout(lambda : index_overlays(self.window), 100)
        
        #if self.callback != None:
        #    debug(self.callback)
        #    self.callback(response_body)

        if sys.version_info >= (3, 0):
            self.calculate_process_region()
            
        ThreadTracker.remove(self)
 def kill(self):
     #TODO: need to do some cleanup here
     ThreadTracker.set_current(self.window_id, None)
def handle_result(operation, process_id, printer, result, thread):
    #print(thread.process_id)
    #print(thread.params)
    process_region = printer.panel.find(process_id,0)
    status_region = printer.panel.find('Result:',process_region.begin())

    try:
        result = json.loads(result)
        if operation == 'compile' and 'actions' in result and util.to_bool(result['success']) == False:
            diff_merge_settings = config.settings.get('mm_diff_server_conflicts', False)
            if diff_merge_settings:
                if sublime.ok_cancel_dialog(result["body"], result["actions"][0].title()):
                    printer.panel.run_command('write_operation_status', {"text": " Diffing with server", 'region': [status_region.end(), status_region.end()+10] })
                    th = MavensMateDiffThread(thread.window, thread.view, result['tmp_file_path'])
                    th.start()
                    
                else:
                    printer.panel.run_command('write_operation_status', {"text": " "+result["actions"][1].title(), 'region': [status_region.end(), status_region.end()+10] })
            else:
                if sublime.ok_cancel_dialog(result["body"], "Overwrite Server Copy"):
                    printer.panel.run_command('write_operation_status', {"text": " Overwriting server copy", 'region': [status_region.end(), status_region.end()+10] })
                    thread.params['action'] = 'overwrite'
                    sublime.set_timeout(lambda: call('compile', params=thread.params), 100)   
                else:
                    printer.panel.run_command('write_operation_status', {"text": " "+result["actions"][1].title(), 'region': [status_region.end(), status_region.end()+10] })
   
        elif operation == 'test_async':
            responses = []
            if len(result) == 1:
                res = result[0]
                response_string = ""
                if 'detailed_results' in res:
                    all_tests_passed = True
                    for r in res['detailed_results']:
                        if r["Outcome"] != "Pass":
                            all_tests_passed = False
                            break

                    if all_tests_passed:
                        response_string += '[TEST RESULT]: PASS'
                    else:
                        response_string += '[TEST RESULT]: FAIL'
                    
                    for r in res['detailed_results']:
                        if r["Outcome"] == "Pass":
                            pass #dont need to write anything here...
                        else:
                            response_string += '\n'
                            rstring = "====METHOD RESULT===="
                            rstring += "\n"
                            rstring += "{0} : {1}".format(r["MethodName"], r["Outcome"])
                            
                            rstring += "\n\n"
                            rstring += "====STACK TRACE===="
                            rstring += "\n"
                            rstring += r["StackTrace"]

                            rstring += "\n\n"
                            rstring += "====MESSAGE===="
                            rstring += "\n"
                            rstring += r["Message"]
                            rstring += "\n"
                            #responses.append("{0} | {1} | {2} | {3}\n".format(r["MethodName"], r["Outcome"], r["StackTrace"], r["Message"]))
                            responses.append(rstring)
                    response_string += "\n"       
                    response_string += "\n\n".join(responses)
                    printer.panel.run_command('write_operation_status', {'text': response_string, 'region': [status_region.end(), status_region.end()+10] })
                    printer.scroll_to_bottom()
                else:
                    printer.panel.run_command('write_operation_status', {'text': json.dumps(result), 'region': [status_region.end(), status_region.end()+10] })
            else:
                pass #TODO
        
        elif operation == 'run_apex_script':
            if result["success"] == True and result["compiled"] == True:
                printer.panel.run_command('write_operation_status', {'text': " Success", 'region': [status_region.end(), status_region.end()+10] })
                thread.window.open_file(result["log_location"], sublime.TRANSIENT)
            elif result["success"] == False:
                message = " [OPERATION FAILED]: "
                if "compileProblem" in result and result["compileProblem"] != None:
                    message += "[Line: "+str(result["line"]) + ", Column: "+str(result["column"])+"] " + result["compileProblem"] + "\n"
                if "exceptionMessage" in result and result["exceptionMessage"] != None:
                    message += result["exceptionMessage"] + "\n"
                if "exceptionStackTrace" in result and result["exceptionStackTrace"] != None:
                    message += result["exceptionStackTrace"] + "\n"
                printer.panel.run_command('write_operation_status', {'text': message, 'region': [status_region.end(), status_region.end()+10] })
        else:
            print_result_message(operation, process_id, status_region, result, printer, thread) 
            if operation == 'new_metadata' and 'success' in result and util.to_bool(result['success']) == True:
                if 'messages' in result:
                    if type(result['messages']) is not list:
                        result['messages'] = [result['messages']]
                    for m in result['messages']:
                        if 'package.xml' not in m['fileName']:
                            file_name = m['fileName']
                            location = os.path.join(util.mm_project_directory(),file_name.replace('unpackaged/', 'src/'))
                            sublime.active_window().open_file(location)
                            break
            if 'success' in result and util.to_bool(result['success']) == True:
                if printer != None and len(ThreadTracker.get_pending_mm_panel_threads(thread.window)) == 0:
                    printer.hide()  
            elif 'State' in result and result['State'] == 'Completed' and len(ThreadTracker.get_pending_mm_panel_threads(thread.window)) == 0:
                #tooling api
                if printer != None:
                    printer.hide()
            if operation == 'refresh':            
                sublime.set_timeout(lambda: sublime.active_window().active_view().run_command('revert'), 200)
                util.clear_marked_line_numbers()
    except AttributeError as e:   
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: '+result+'\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: '+result
            print(e)
            print(sys.exc_info()[0])
            printer.panel.run_command('write_operation_status', {'text': msg, 'region': [status_region.end(), status_region.end()+10] })
    except Exception as e:
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: '+result+'\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: '+result
            print(e)
            print(sys.exc_info()[0])
            printer.panel.run_command('write_operation_status', {'text': msg, 'region': [status_region.end(), status_region.end()+10] })
def handle_result(operation, process_id, printer, result, thread):
    #print(thread.process_id)
    #print(thread.params)
    process_region = printer.panel.find(process_id, 0)
    status_region = printer.panel.find('Result:', process_region.begin())

    try:
        result = json.loads(result)
        if operation == 'compile' and 'actions' in result and util.to_bool(
                result['success']) == False:
            diff_merge_settings = config.settings.get(
                'mm_diff_server_conflicts', False)
            if diff_merge_settings:
                if sublime.ok_cancel_dialog(result["body"],
                                            result["actions"][0].title()):
                    printer.panel.run_command(
                        'write_operation_status', {
                            "text":
                            " Diffing with server",
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })
                    th = MavensMateDiffThread(thread.window, thread.view,
                                              result['tmp_file_path'])
                    th.start()

                else:
                    printer.panel.run_command(
                        'write_operation_status', {
                            "text":
                            " " + result["actions"][1].title(),
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })
            else:
                if sublime.ok_cancel_dialog(result["body"],
                                            "Overwrite Server Copy"):
                    printer.panel.run_command(
                        'write_operation_status', {
                            "text":
                            " Overwriting server copy",
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })
                    thread.params['action'] = 'overwrite'
                    sublime.set_timeout(
                        lambda: call('compile', params=thread.params), 100)
                else:
                    printer.panel.run_command(
                        'write_operation_status', {
                            "text":
                            " " + result["actions"][1].title(),
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })

        elif operation == 'test_async':
            responses = []
            if len(result) == 1:
                res = result[0]
                response_string = ""
                if 'detailed_results' in res:
                    all_tests_passed = True
                    for r in res['detailed_results']:
                        if r["Outcome"] != "Pass":
                            all_tests_passed = False
                            break

                    if all_tests_passed:
                        response_string += '[TEST RESULT]: PASS'
                    else:
                        response_string += '[TEST RESULT]: FAIL'

                    for r in res['detailed_results']:
                        if r["Outcome"] == "Pass":
                            pass  #dont need to write anything here...
                        else:
                            response_string += '\n'
                            rstring = "====METHOD RESULT===="
                            rstring += "\n"
                            rstring += "{0} : {1}".format(
                                r["MethodName"], r["Outcome"])

                            rstring += "\n\n"
                            rstring += "====STACK TRACE===="
                            rstring += "\n"
                            rstring += r["StackTrace"]

                            rstring += "\n\n"
                            rstring += "====MESSAGE===="
                            rstring += "\n"
                            rstring += r["Message"]
                            rstring += "\n"
                            #responses.append("{0} | {1} | {2} | {3}\n".format(r["MethodName"], r["Outcome"], r["StackTrace"], r["Message"]))
                            responses.append(rstring)
                    response_string += "\n"
                    response_string += "\n\n".join(responses)
                    printer.panel.run_command(
                        'write_operation_status', {
                            'text':
                            response_string,
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })
                    printer.scroll_to_bottom()
                else:
                    printer.panel.run_command(
                        'write_operation_status', {
                            'text':
                            json.dumps(result),
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })
            else:
                pass  #TODO

        elif operation == 'run_apex_script':
            if result["success"] == True and result["compiled"] == True:
                printer.panel.run_command(
                    'write_operation_status', {
                        'text': " Success",
                        'region':
                        [status_region.end(),
                         status_region.end() + 10]
                    })
                thread.window.open_file(result["log_location"],
                                        sublime.TRANSIENT)
            elif result["success"] == False:
                message = " [OPERATION FAILED]: "
                if "compileProblem" in result and result[
                        "compileProblem"] != None:
                    message += "[Line: " + str(
                        result["line"]) + ", Column: " + str(
                            result["column"]
                        ) + "] " + result["compileProblem"] + "\n"
                if "exceptionMessage" in result and result[
                        "exceptionMessage"] != None:
                    message += result["exceptionMessage"] + "\n"
                if "exceptionStackTrace" in result and result[
                        "exceptionStackTrace"] != None:
                    message += result["exceptionStackTrace"] + "\n"
                printer.panel.run_command(
                    'write_operation_status', {
                        'text': message,
                        'region':
                        [status_region.end(),
                         status_region.end() + 10]
                    })
        else:
            print_result_message(operation, process_id, status_region, result,
                                 printer, thread)
            if operation == 'new_metadata' and 'success' in result and util.to_bool(
                    result['success']) == True:
                if 'messages' in result:
                    if type(result['messages']) is not list:
                        result['messages'] = [result['messages']]
                    for m in result['messages']:
                        if 'package.xml' not in m['fileName']:
                            file_name = m['fileName']
                            location = os.path.join(
                                util.mm_project_directory(),
                                file_name.replace('unpackaged/', 'src/'))
                            sublime.active_window().open_file(location)
                            break
            if 'success' in result and util.to_bool(result['success']) == True:
                if printer != None and len(
                        ThreadTracker.get_pending_mm_panel_threads(
                            thread.window)) == 0:
                    printer.hide()
            elif 'State' in result and result['State'] == 'Completed' and len(
                    ThreadTracker.get_pending_mm_panel_threads(
                        thread.window)) == 0:
                #tooling api
                if printer != None:
                    printer.hide()
            if operation == 'refresh':
                sublime.set_timeout(
                    lambda: sublime.active_window().active_view().run_command(
                        'revert'), 200)
                util.clear_marked_line_numbers()
    except AttributeError as e:
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: ' + result + '\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: ' + result
            print(e)
            print(sys.exc_info()[0])
            printer.panel.run_command(
                'write_operation_status', {
                    'text': msg,
                    'region': [status_region.end(),
                               status_region.end() + 10]
                })
    except Exception as e:
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: ' + result + '\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: ' + result
            print(e)
            print(sys.exc_info()[0])
            printer.panel.run_command(
                'write_operation_status', {
                    'text': msg,
                    'region': [status_region.end(),
                               status_region.end() + 10]
                })
def handle_result(operation, process_id, printer, result, thread):
    #print(thread.process_id)
    #print(thread.params)
    process_region = printer.panel.find(process_id, 0)
    status_region = printer.panel.find('Result:', process_region.begin())

    try:
        result = json.loads(result)
        if operation == 'compile' and 'actions' in result and util.to_bool(
                result['success']) == False:
            diff_merge_settings = config.settings.get(
                'mm_diff_server_conflicts', False)
            if diff_merge_settings:
                if sublime.ok_cancel_dialog(result["body"],
                                            result["actions"][0].title()):
                    printer.panel.run_command(
                        'write_operation_status', {
                            "text":
                            " Diffing with server",
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })
                    th = MavensMateDiffThread(thread.window, thread.view,
                                              result['tmp_file_path'])
                    th.start()

                else:
                    printer.panel.run_command(
                        'write_operation_status', {
                            "text":
                            " " + result["actions"][1].title(),
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })
            else:
                if sublime.ok_cancel_dialog(result["body"],
                                            "Overwrite Server Copy"):
                    printer.panel.run_command(
                        'write_operation_status', {
                            "text":
                            " Overwriting server copy",
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })
                    thread.params['action'] = 'overwrite'
                    sublime.set_timeout(
                        lambda: call('compile', params=thread.params), 100)
                else:
                    printer.panel.run_command(
                        'write_operation_status', {
                            "text":
                            " " + result["actions"][1].title(),
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })

        else:
            print_result_message(operation, process_id, status_region, result,
                                 printer, thread)
            if operation == 'new_metadata' and 'success' in result and util.to_bool(
                    result['success']) == True:
                if 'messages' in result:
                    if type(result['messages']) is not list:
                        result['messages'] = [result['messages']]
                    for m in result['messages']:
                        if 'package.xml' not in m['fileName']:
                            file_name = m['fileName']
                            location = util.mm_project_directory(
                            ) + "/" + file_name.replace('unpackaged/', 'src/')
                            sublime.active_window().open_file(location)
                            break
            if 'success' in result and util.to_bool(result['success']) == True:
                if printer != None and len(
                        ThreadTracker.get_pending_mm_panel_threads(
                            thread.window)) == 0:
                    printer.hide()
            elif 'State' in result and result['State'] == 'Completed' and len(
                    ThreadTracker.get_pending_mm_panel_threads(
                        thread.window)) == 0:
                #tooling api
                if printer != None:
                    printer.hide()
            if operation == 'refresh':
                sublime.set_timeout(
                    lambda: sublime.active_window().active_view().run_command(
                        'revert'), 200)
                util.clear_marked_line_numbers()
    except AttributeError:
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: ' + result + '\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: ' + result
            printer.panel.run_command(
                'write_operation_status', {
                    'text': msg,
                    'region': [status_region.end(),
                               status_region.end() + 10]
                })
    except Exception:
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: ' + result + '\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: ' + result
            printer.panel.run_command(
                'write_operation_status', {
                    'text': msg,
                    'region': [status_region.end(),
                               status_region.end() + 10]
                })
    def run(self):
        if self.use_mm_panel:
            if sys.version_info >= (3, 0):
                self.calculate_process_region()
            PanelThreadProgress(self)

        #last_thread = ThreadTracker.get_last_added(self.window)
        ThreadTracker.add(self)

        if self.settings.get('mm_debug_mode'):
            python_path = self.settings.get('mm_python_location')
            mm_loc = self.settings.get('mm_debug_location')
            print('[MAVENSMATE] executing DEBUG mm terminal call:')
            print("{0} {1} {2}".format(python_path, pipes.quote(mm_loc),
                                       self.get_arguments()))
            process = subprocess.Popen("{0} {1} {2}".format(
                python_path, pipes.quote(mm_loc), self.get_arguments()),
                                       stdin=subprocess.PIPE,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.STDOUT,
                                       shell=True)
        else:
            print('[MAVENSMATE] executing mm terminal call:')
            print("{0} {1}".format(pipes.quote(self.mm_location),
                                   self.get_arguments()))
            process = subprocess.Popen("{0} {1}".format(
                self.mm_location, self.get_arguments()),
                                       cwd=sublime.packages_path(),
                                       stdin=subprocess.PIPE,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.STDOUT,
                                       shell=True)
        self.submit_payload(process)
        if process.stdout is not None:
            mm_response = process.stdout.readlines()
        elif process.stderr is not None:
            mm_response = process.stderr.readlines()
        try:
            response_body = '\n'.join(mm_response)
        except:
            strs = []
            for line in mm_response:
                strs.append(line.decode('utf-8'))
            response_body = '\n'.join(strs)

        print('[MAVENSMATE] response from mm: ' + response_body)
        self.result = response_body
        if self.operation == 'compile':
            compile_callback(self, response_body)

        #if self.operation == 'new_apex_overlay' or self.operation == 'delete_apex_overlay':
        #    sublime.set_timeout(lambda : index_overlays(self.window), 100)

        #if self.callback != None:
        #    print(self.callback)
        #    self.callback(response_body)

        if sys.version_info >= (3, 0):
            self.calculate_process_region()

        ThreadTracker.remove(self)