FlatCAMApp.py 264 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import sys
  9. import traceback
  10. import urllib.request, urllib.parse, urllib.error
  11. import getopt
  12. import os
  13. import random
  14. import logging
  15. import simplejson as json
  16. import re
  17. import os
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import subprocess
  20. import tkinter as tk
  21. from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
  22. import time # Just used for debugging. Double check before removing.
  23. import urllib.request, urllib.parse, urllib.error
  24. import webbrowser
  25. from contextlib import contextmanager
  26. from xml.dom.minidom import parseString as parse_xml_string
  27. from copy import copy,deepcopy
  28. import numpy as np
  29. from datetime import datetime
  30. import gc
  31. ########################################
  32. ## Imports part of FlatCAM ##
  33. ########################################
  34. from ObjectCollection import *
  35. from FlatCAMObj import *
  36. from PlotCanvas import *
  37. from FlatCAMGUI import *
  38. from FlatCAMCommon import LoudDict
  39. from FlatCAMPostProc import load_postprocessors
  40. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  41. from FlatCAMProcess import *
  42. from FlatCAMWorkerStack import WorkerStack
  43. from VisPyVisuals import Color
  44. from vispy.gloo.util import _screenshot
  45. from vispy.io import write_png
  46. from flatcamTools import *
  47. from multiprocessing import Pool
  48. import tclCommands
  49. # from ParseFont import *
  50. ########################################
  51. ## App ##
  52. ########################################
  53. class App(QtCore.QObject):
  54. """
  55. The main application class. The constructor starts the GUI.
  56. """
  57. # Get Cmd Line Options
  58. cmd_line_shellfile = ''
  59. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  60. try:
  61. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  62. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  63. except getopt.GetoptError:
  64. print(cmd_line_help)
  65. sys.exit(2)
  66. for opt, arg in cmd_line_options:
  67. if opt == '-h':
  68. print(cmd_line_help)
  69. sys.exit()
  70. elif opt == '--shellfile':
  71. cmd_line_shellfile = arg
  72. # Logging ##
  73. log = logging.getLogger('base')
  74. log.setLevel(logging.DEBUG)
  75. # log.setLevel(logging.WARNING)
  76. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  77. handler = logging.StreamHandler()
  78. handler.setFormatter(formatter)
  79. log.addHandler(handler)
  80. # Version
  81. version = 8.906
  82. version_date = "2019/02/1"
  83. beta = True
  84. # URL for update checks and statistics
  85. version_url = "http://flatcam.org/version"
  86. # App URL
  87. app_url = "http://flatcam.org"
  88. # Manual URL
  89. manual_url = "http://flatcam.org/manual/index.html"
  90. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  91. should_we_quit = True
  92. ##################
  93. ## Signals ##
  94. ##################
  95. # Inform the user
  96. # Handled by:
  97. # * App.info() --> Print on the status bar
  98. inform = QtCore.pyqtSignal(str)
  99. # General purpose background task
  100. worker_task = QtCore.pyqtSignal(dict)
  101. # File opened
  102. # Handled by:
  103. # * register_folder()
  104. # * register_recent()
  105. # Note: Setting the parameters to unicode does not seem
  106. # to have an effect. Then are received as Qstring
  107. # anyway.
  108. # File type and filename
  109. file_opened = QtCore.pyqtSignal(str, str)
  110. # File type and filename
  111. file_saved = QtCore.pyqtSignal(str, str)
  112. # Percentage of progress
  113. progress = QtCore.pyqtSignal(int)
  114. plots_updated = QtCore.pyqtSignal()
  115. # Emitted by new_object() and passes the new object as argument, plot flag.
  116. # on_object_created() adds the object to the collection, plots on appropriate flag
  117. # and emits new_object_available.
  118. object_created = QtCore.pyqtSignal(object, bool, bool)
  119. # Emitted when a object has been changed (like scaled, mirrored)
  120. object_changed = QtCore.pyqtSignal(object)
  121. # Emitted after object has been plotted.
  122. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  123. object_plotted = QtCore.pyqtSignal(object)
  124. # Emitted when a new object has been added to the collection
  125. # and is ready to be used.
  126. new_object_available = QtCore.pyqtSignal(object)
  127. message = QtCore.pyqtSignal(str, str, str)
  128. # Emmited when shell command is finished(one command only)
  129. shell_command_finished = QtCore.pyqtSignal(object)
  130. # Emitted when multiprocess pool has been recreated
  131. pool_recreated = QtCore.pyqtSignal(object)
  132. # Emitted when an unhandled exception happens
  133. # in the worker task.
  134. thread_exception = QtCore.pyqtSignal(object)
  135. def __init__(self, user_defaults=True, post_gui=None):
  136. """
  137. Starts the application.
  138. :return: app
  139. :rtype: App
  140. """
  141. App.log.info("FlatCAM Starting...")
  142. ###################
  143. ### OS-specific ###
  144. ###################
  145. # Folder for user settings.
  146. if sys.platform == 'win32':
  147. from win32com.shell import shell, shellcon
  148. if platform.architecture()[0] == '32bit':
  149. App.log.debug("Win32!")
  150. else:
  151. App.log.debug("Win64!")
  152. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  153. '\FlatCAM'
  154. self.os = 'windows'
  155. else: # Linux/Unix/MacOS
  156. self.data_path = os.path.expanduser('~') + \
  157. '/.FlatCAM'
  158. self.os = 'unix'
  159. ###############################
  160. ### Setup folders and files ###
  161. ###############################
  162. if not os.path.exists(self.data_path):
  163. os.makedirs(self.data_path)
  164. App.log.debug('Created data folder: ' + self.data_path)
  165. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  166. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  167. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  168. if not os.path.exists(self.postprocessorpaths):
  169. os.makedirs(self.postprocessorpaths)
  170. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  171. # create current_defaults.FlatConfig file if there is none
  172. try:
  173. f = open(self.data_path + '/current_defaults.FlatConfig')
  174. f.close()
  175. except IOError:
  176. App.log.debug('Creating empty current_defaults.FlatConfig')
  177. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  178. json.dump({}, f)
  179. f.close()
  180. # create factory_defaults.FlatConfig file if there is none
  181. try:
  182. f = open(self.data_path + '/factory_defaults.FlatConfig')
  183. f.close()
  184. except IOError:
  185. App.log.debug('Creating empty factory_defaults.FlatConfig')
  186. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  187. json.dump({}, f)
  188. f.close()
  189. try:
  190. f = open(self.data_path + '/recent.json')
  191. f.close()
  192. except IOError:
  193. App.log.debug('Creating empty recent.json')
  194. f = open(self.data_path + '/recent.json', 'w')
  195. json.dump([], f)
  196. f.close()
  197. # Application directory. CHDIR to it. Otherwise, trying to load
  198. # GUI icons will fail as their path is relative.
  199. # This will fail under cx_freeze ...
  200. self.app_home = os.path.dirname(os.path.realpath(__file__))
  201. App.log.debug("Application path is " + self.app_home)
  202. App.log.debug("Started in " + os.getcwd())
  203. # cx_freeze workaround
  204. if os.path.isfile(self.app_home):
  205. self.app_home = os.path.dirname(self.app_home)
  206. os.chdir(self.app_home)
  207. # Create multiprocessing pool
  208. self.pool = Pool()
  209. ####################
  210. ## Initialize GUI ##
  211. ####################
  212. # FlatCAM colors used in plotting
  213. self.FC_light_green = '#BBF268BF'
  214. self.FC_dark_green = '#006E20BF'
  215. self.FC_light_blue = '#a5a5ffbf'
  216. self.FC_dark_blue = '#0000ffbf'
  217. QtCore.QObject.__init__(self)
  218. self.ui = FlatCAMGUI(self.version, self.beta, self)
  219. # self.connect(self.ui,
  220. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  221. # self.save_geometry) PyQt4
  222. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  223. self.ui.final_save.connect(self.final_save)
  224. ##############
  225. #### Data ####
  226. ##############
  227. self.recent = []
  228. self.clipboard = QtWidgets.QApplication.clipboard()
  229. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  230. self.project_filename = None
  231. self.toggle_units_ignore = False
  232. # self.defaults_form = PreferencesUI()
  233. self.general_defaults_form = GeneralPreferencesUI()
  234. self.gerber_defaults_form = GerberPreferencesUI()
  235. self.excellon_defaults_form = ExcellonPreferencesUI()
  236. self.geometry_defaults_form = GeometryPreferencesUI()
  237. self.cncjob_defaults_form = CNCJobPreferencesUI()
  238. self.tools_defaults_form = ToolsPreferencesUI()
  239. # when adding entries here read the comments in the method found bellow named:
  240. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  241. self.defaults_form_fields = {
  242. "units": self.general_defaults_form.general_app_group.units_radio,
  243. "global_shell_at_startup": self.general_defaults_form.general_app_group.shell_startup_cb,
  244. "global_version_check": self.general_defaults_form.general_app_group.version_check_cb,
  245. "global_send_stats": self.general_defaults_form.general_app_group.send_stats_cb,
  246. "global_gridx": self.general_defaults_form.general_gui_group.gridx_entry,
  247. "global_gridy": self.general_defaults_form.general_gui_group.gridy_entry,
  248. "global_plot_fill": self.general_defaults_form.general_gui_group.pf_color_entry,
  249. "global_plot_line": self.general_defaults_form.general_gui_group.pl_color_entry,
  250. "global_sel_fill": self.general_defaults_form.general_gui_group.sf_color_entry,
  251. "global_sel_line": self.general_defaults_form.general_gui_group.sl_color_entry,
  252. "global_alt_sel_fill": self.general_defaults_form.general_gui_group.alt_sf_color_entry,
  253. "global_alt_sel_line": self.general_defaults_form.general_gui_group.alt_sl_color_entry,
  254. "global_draw_color": self.general_defaults_form.general_gui_group.draw_color_entry,
  255. "global_sel_draw_color": self.general_defaults_form.general_gui_group.sel_draw_color_entry,
  256. "global_pan_button": self.general_defaults_form.general_app_group.pan_button_radio,
  257. "global_mselect_key": self.general_defaults_form.general_app_group.mselect_radio,
  258. # "global_pan_with_space_key": self.general_defaults_form.general_gui_group.pan_with_space_cb,
  259. "global_workspace": self.general_defaults_form.general_gui_group.workspace_cb,
  260. "global_workspaceT": self.general_defaults_form.general_gui_group.wk_cb,
  261. "global_theme": self.general_defaults_form.general_gui_group.theme_combo,
  262. "gerber_plot": self.gerber_defaults_form.gerber_gen_group.plot_cb,
  263. "gerber_solid": self.gerber_defaults_form.gerber_gen_group.solid_cb,
  264. "gerber_multicolored": self.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  265. "gerber_circle_steps": self.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  266. "gerber_isotooldia": self.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  267. "gerber_isopasses": self.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  268. "gerber_isooverlap": self.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  269. "gerber_combine_passes": self.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  270. "gerber_milling_type": self.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  271. "gerber_noncoppermargin": self.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  272. "gerber_noncopperrounded": self.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  273. "gerber_bboxmargin": self.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  274. "gerber_bboxrounded": self.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  275. "excellon_plot": self.excellon_defaults_form.excellon_gen_group.plot_cb,
  276. "excellon_solid": self.excellon_defaults_form.excellon_gen_group.solid_cb,
  277. "excellon_format_upper_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  278. "excellon_format_lower_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  279. "excellon_format_upper_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  280. "excellon_format_lower_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  281. "excellon_zeros": self.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  282. "excellon_units": self.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  283. "excellon_optimization_type": self.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  284. "excellon_search_time": self.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  285. "excellon_drillz": self.excellon_defaults_form.excellon_opt_group.cutz_entry,
  286. "excellon_travelz": self.excellon_defaults_form.excellon_opt_group.travelz_entry,
  287. "excellon_feedrate": self.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  288. "excellon_feedrate_rapid": self.excellon_defaults_form.excellon_opt_group.feedrate_rapid_entry,
  289. "excellon_spindlespeed": self.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  290. "excellon_dwell": self.excellon_defaults_form.excellon_opt_group.dwell_cb,
  291. "excellon_dwelltime": self.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  292. "excellon_toolchange": self.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  293. "excellon_toolchangez": self.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  294. "excellon_toolchangexy": self.excellon_defaults_form.excellon_opt_group.toolchangexy_entry,
  295. "excellon_ppname_e": self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  296. "excellon_f_plunge": self.excellon_defaults_form.excellon_opt_group.fplunge_cb,
  297. "excellon_startz": self.excellon_defaults_form.excellon_opt_group.estartz_entry,
  298. "excellon_endz": self.excellon_defaults_form.excellon_opt_group.eendz_entry,
  299. "excellon_tooldia": self.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  300. "excellon_slot_tooldia": self.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  301. "excellon_gcode_type": self.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  302. "geometry_plot": self.geometry_defaults_form.geometry_gen_group.plot_cb,
  303. "geometry_cnctooldia": self.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  304. "geometry_circle_steps": self.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  305. "geometry_segx": self.geometry_defaults_form.geometry_opt_group.segx_entry,
  306. "geometry_segy": self.geometry_defaults_form.geometry_opt_group.segy_entry,
  307. "geometry_cutz": self.geometry_defaults_form.geometry_opt_group.cutz_entry,
  308. "geometry_travelz": self.geometry_defaults_form.geometry_opt_group.travelz_entry,
  309. "geometry_feedrate": self.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  310. "geometry_feedrate_z": self.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  311. "geometry_feedrate_rapid": self.geometry_defaults_form.geometry_opt_group.cncfeedrate_rapid_entry,
  312. "geometry_spindlespeed": self.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  313. "geometry_dwell": self.geometry_defaults_form.geometry_opt_group.dwell_cb,
  314. "geometry_dwelltime": self.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  315. "geometry_ppname_g": self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  316. "geometry_f_plunge": self.geometry_defaults_form.geometry_opt_group.fplunge_cb,
  317. "geometry_toolchange": self.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  318. "geometry_toolchangez": self.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  319. "geometry_toolchangexy": self.geometry_defaults_form.geometry_opt_group.toolchangexy_entry,
  320. "geometry_startz": self.geometry_defaults_form.geometry_opt_group.gstartz_entry,
  321. "geometry_endz": self.geometry_defaults_form.geometry_opt_group.gendz_entry,
  322. "geometry_multidepth": self.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  323. "geometry_depthperpass": self.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  324. "geometry_extracut": self.geometry_defaults_form.geometry_opt_group.extracut_cb,
  325. "cncjob_plot": self.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  326. "cncjob_tooldia": self.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  327. "cncjob_coords_decimals": self.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  328. "cncjob_fr_decimals": self.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  329. "cncjob_steps_per_circle": self.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  330. "cncjob_prepend": self.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  331. "cncjob_append": self.cncjob_defaults_form.cncjob_opt_group.append_text,
  332. "tools_ncctools": self.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  333. "tools_nccoverlap": self.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  334. "tools_nccmargin": self.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  335. "tools_nccmethod": self.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  336. "tools_nccconnect": self.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  337. "tools_ncccontour": self.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  338. "tools_nccrest": self.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  339. "tools_cutouttooldia": self.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  340. "tools_cutoutmargin": self.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  341. "tools_cutoutgapsize": self.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  342. "tools_gaps_rect": self.tools_defaults_form.tools_cutout_group.gaps_radio,
  343. "tools_gaps_ff": self.tools_defaults_form.tools_cutout_group.gaps_combo,
  344. "tools_painttooldia": self.tools_defaults_form.tools_paint_group.painttooldia_entry,
  345. "tools_paintoverlap": self.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  346. "tools_paintmargin": self.tools_defaults_form.tools_paint_group.paintmargin_entry,
  347. "tools_paintmethod": self.tools_defaults_form.tools_paint_group.paintmethod_combo,
  348. "tools_selectmethod": self.tools_defaults_form.tools_paint_group.selectmethod_combo,
  349. "tools_pathconnect": self.tools_defaults_form.tools_paint_group.pathconnect_cb,
  350. "tools_paintcontour": self.tools_defaults_form.tools_paint_group.contour_cb,
  351. "tools_2sided_mirror_axis": self.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  352. "tools_2sided_axis_loc": self.tools_defaults_form.tools_2sided_group.axis_location_radio,
  353. "tools_2sided_drilldia": self.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  354. }
  355. # loads postprocessors
  356. self.postprocessors = load_postprocessors(self)
  357. for name in list(self.postprocessors.keys()):
  358. self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  359. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  360. if name == 'hpgl':
  361. continue
  362. self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  363. self.defaults = LoudDict()
  364. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  365. self.defaults.update({
  366. "global_serial": 0,
  367. "global_stats": {},
  368. "units": "IN",
  369. "global_version_check": True,
  370. "global_send_stats": True,
  371. "global_gridx": 1.0,
  372. "global_gridy": 1.0,
  373. "global_plot_fill": '#BBF268BF',
  374. "global_plot_line": '#006E20BF',
  375. "global_sel_fill": '#a5a5ffbf',
  376. "global_sel_line": '#0000ffbf',
  377. "global_alt_sel_fill": '#BBF268BF',
  378. "global_alt_sel_line": '#006E20BF',
  379. "global_draw_color": '#FF0000',
  380. "global_sel_draw_color": '#0000FF',
  381. "global_pan_button": '2',
  382. "global_mselect_key": 'Control',
  383. # "global_pan_with_space_key": False,
  384. "global_workspace": False,
  385. "global_workspaceT": "A4P",
  386. "global_toolbar_view": 31,
  387. "global_background_timeout": 300000, # Default value is 5 minutes
  388. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  389. # (python trace only for unknown errors),
  390. # 1 = show trace(show trace allways),
  391. # 2 = (For the future).
  392. # Persistence
  393. "global_last_folder": None,
  394. "global_last_save_folder": None,
  395. # Default window geometry
  396. "global_def_win_x": 100,
  397. "global_def_win_y": 100,
  398. "global_def_win_w": 1024,
  399. "global_def_win_h": 650,
  400. "global_theme": 'standard',
  401. # Constants...
  402. "global_defaults_save_period_ms": 20000, # Time between default saves.
  403. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  404. "global_shell_at_startup": False, # Show the shell at startup.
  405. "global_recent_limit": 10, # Max. items in recent list.
  406. "fit_key": '1',
  407. "zoom_out_key": '2',
  408. "zoom_in_key": '3',
  409. "grid_toggle_key": 'G',
  410. "zoom_ratio": 1.5,
  411. "global_point_clipboard_format": "(%.4f, %.4f)",
  412. "global_zdownrate": None,
  413. "gerber_plot": True,
  414. "gerber_solid": True,
  415. "gerber_multicolored": False,
  416. "gerber_isotooldia": 0.016,
  417. "gerber_isopasses": 1,
  418. "gerber_isooverlap": 0.15,
  419. "gerber_combine_passes": False,
  420. "gerber_milling_type": "cl",
  421. "gerber_noncoppermargin": 0.1,
  422. "gerber_noncopperrounded": False,
  423. "gerber_bboxmargin": 0.1,
  424. "gerber_bboxrounded": False,
  425. "gerber_circle_steps": 64,
  426. "gerber_use_buffer_for_union": True,
  427. "excellon_plot": True,
  428. "excellon_solid": True,
  429. "excellon_format_upper_in": 2,
  430. "excellon_format_lower_in": 4,
  431. "excellon_format_upper_mm": 3,
  432. "excellon_format_lower_mm": 3,
  433. "excellon_zeros": "L",
  434. "excellon_units": "INCH",
  435. "excellon_optimization_type": 'B',
  436. "excellon_search_time": 3,
  437. "excellon_drillz": -0.1,
  438. "excellon_travelz": 0.1,
  439. "excellon_feedrate": 3.0,
  440. "excellon_feedrate_rapid": 3.0,
  441. "excellon_spindlespeed": None,
  442. "excellon_dwell": False,
  443. "excellon_dwelltime": 1,
  444. "excellon_toolchange": False,
  445. "excellon_toolchangez": 1.0,
  446. "excellon_toolchangexy": "0.0, 0.0",
  447. "excellon_tooldia": 0.016,
  448. "excellon_slot_tooldia": 0.016,
  449. "excellon_startz": None,
  450. "excellon_endz": 2.0,
  451. "excellon_ppname_e": 'default',
  452. "excellon_f_plunge": False,
  453. "excellon_gcode_type": "drills",
  454. "geometry_plot": True,
  455. "geometry_segx": 0.0,
  456. "geometry_segy": 0.0,
  457. "geometry_cutz": -0.002,
  458. "geometry_travelz": 0.1,
  459. "geometry_toolchange": False,
  460. "geometry_toolchangez": 1.0,
  461. "geometry_toolchangexy": "0.0, 0.0",
  462. "geometry_startz": None,
  463. "geometry_endz": 2.0,
  464. "geometry_feedrate": 3.0,
  465. "geometry_feedrate_z": 3.0,
  466. "geometry_feedrate_rapid": 3.0,
  467. "geometry_cnctooldia": 0.016,
  468. "geometry_spindlespeed": None,
  469. "geometry_dwell": False,
  470. "geometry_dwelltime": 1,
  471. "geometry_ppname_g": 'default',
  472. "geometry_f_plunge": False,
  473. "geometry_depthperpass": 0.002,
  474. "geometry_multidepth": False,
  475. "geometry_extracut": False,
  476. "geometry_circle_steps": 64,
  477. "cncjob_plot": True,
  478. "cncjob_tooldia": 0.0393701,
  479. "cncjob_coords_decimals": 4,
  480. "cncjob_fr_decimals": 2,
  481. "cncjob_prepend": "",
  482. "cncjob_append": "",
  483. "cncjob_steps_per_circle": 64,
  484. "tools_ncctools": "1.0, 0.5",
  485. "tools_nccoverlap": 0.4,
  486. "tools_nccmargin": 0.1,
  487. "tools_nccmethod": "seed",
  488. "tools_nccconnect": True,
  489. "tools_ncccontour": True,
  490. "tools_nccrest": False,
  491. "tools_cutouttooldia": 0.1,
  492. "tools_cutoutmargin": 0.1,
  493. "tools_cutoutgapsize": 0.15,
  494. "tools_gaps_rect": "4",
  495. "tools_gaps_ff": "8",
  496. "tools_painttooldia": 0.07,
  497. "tools_paintoverlap": 0.15,
  498. "tools_paintmargin": 0.0,
  499. "tools_paintmethod": "seed",
  500. "tools_selectmethod": "single",
  501. "tools_pathconnect": True,
  502. "tools_paintcontour": True,
  503. "tools_2sided_mirror_axis": "X",
  504. "tools_2sided_axis_loc": "point",
  505. "tools_2sided_drilldia": 1,
  506. })
  507. ###############################
  508. ### Load defaults from file ###
  509. if user_defaults:
  510. self.load_defaults(filename='current_defaults')
  511. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  512. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  513. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  514. self.save_defaults(silent=True)
  515. self.propagate_defaults(silent=True)
  516. self.restore_main_win_geom()
  517. def auto_save_defaults():
  518. try:
  519. self.save_defaults(silent=True)
  520. self.propagate_defaults(silent=True)
  521. finally:
  522. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  523. # the following lines activates automatic defaults save
  524. # if user_defaults:
  525. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  526. # self.options_form = PreferencesUI()
  527. self.general_options_form = GeneralPreferencesUI()
  528. self.gerber_options_form = GerberPreferencesUI()
  529. self.excellon_options_form = ExcellonPreferencesUI()
  530. self.geometry_options_form = GeometryPreferencesUI()
  531. self.cncjob_options_form = CNCJobPreferencesUI()
  532. self.tools_options_form = ToolsPreferencesUI()
  533. self.options_form_fields = {
  534. "units": self.general_options_form.general_app_group.units_radio,
  535. "global_gridx": self.general_options_form.general_gui_group.gridx_entry,
  536. "global_gridy": self.general_options_form.general_gui_group.gridy_entry,
  537. "global_theme": self.general_options_form.general_gui_group.theme_combo,
  538. "gerber_plot": self.gerber_options_form.gerber_gen_group.plot_cb,
  539. "gerber_solid": self.gerber_options_form.gerber_gen_group.solid_cb,
  540. "gerber_multicolored": self.gerber_options_form.gerber_gen_group.multicolored_cb,
  541. "gerber_isotooldia": self.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  542. "gerber_isopasses": self.gerber_options_form.gerber_opt_group.iso_width_entry,
  543. "gerber_isooverlap": self.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  544. "gerber_combine_passes": self.gerber_options_form.gerber_opt_group.combine_passes_cb,
  545. "gerber_noncoppermargin": self.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  546. "gerber_noncopperrounded": self.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  547. "gerber_bboxmargin": self.gerber_options_form.gerber_opt_group.bbmargin_entry,
  548. "gerber_bboxrounded": self.gerber_options_form.gerber_opt_group.bbrounded_cb,
  549. "excellon_plot": self.excellon_options_form.excellon_gen_group.plot_cb,
  550. "excellon_solid": self.excellon_options_form.excellon_gen_group.solid_cb,
  551. "excellon_format_upper_in": self.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  552. "excellon_format_lower_in": self.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  553. "excellon_format_upper_mm": self.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  554. "excellon_format_lower_mm": self.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  555. "excellon_zeros": self.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  556. "excellon_units": self.excellon_options_form.excellon_gen_group.excellon_units_radio,
  557. "excellon_optimization_type": self.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  558. "excellon_drillz": self.excellon_options_form.excellon_opt_group.cutz_entry,
  559. "excellon_travelz": self.excellon_options_form.excellon_opt_group.travelz_entry,
  560. "excellon_feedrate": self.excellon_options_form.excellon_opt_group.feedrate_entry,
  561. "excellon_feedrate_rapid": self.excellon_options_form.excellon_opt_group.feedrate_rapid_entry,
  562. "excellon_spindlespeed": self.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  563. "excellon_dwell": self.excellon_options_form.excellon_opt_group.dwell_cb,
  564. "excellon_dwelltime": self.excellon_options_form.excellon_opt_group.dwelltime_entry,
  565. "excellon_toolchange": self.excellon_options_form.excellon_opt_group.toolchange_cb,
  566. "excellon_toolchangez": self.excellon_options_form.excellon_opt_group.toolchangez_entry,
  567. "excellon_toolchangexy": self.excellon_options_form.excellon_opt_group.toolchangexy_entry,
  568. "excellon_tooldia": self.excellon_options_form.excellon_opt_group.tooldia_entry,
  569. "excellon_ppname_e": self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  570. "excellon_f_plunge": self.excellon_options_form.excellon_opt_group.fplunge_cb,
  571. "excellon_startz": self.excellon_options_form.excellon_opt_group.estartz_entry,
  572. "excellon_endz": self.excellon_options_form.excellon_opt_group.eendz_entry,
  573. "geometry_plot": self.geometry_options_form.geometry_gen_group.plot_cb,
  574. "geometry_cnctooldia": self.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  575. "geometry_segx": self.geometry_options_form.geometry_opt_group.segx_entry,
  576. "geometry_segy": self.geometry_options_form.geometry_opt_group.segy_entry,
  577. "geometry_cutz": self.geometry_options_form.geometry_opt_group.cutz_entry,
  578. "geometry_travelz": self.geometry_options_form.geometry_opt_group.travelz_entry,
  579. "geometry_feedrate": self.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  580. "geometry_feedrate_z": self.geometry_options_form.geometry_opt_group.cncplunge_entry,
  581. "geometry_feedrate_rapid": self.geometry_options_form.geometry_opt_group.cncfeedrate_rapid_entry,
  582. "geometry_spindlespeed": self.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  583. "geometry_dwell": self.geometry_options_form.geometry_opt_group.dwell_cb,
  584. "geometry_dwelltime": self.geometry_options_form.geometry_opt_group.dwelltime_entry,
  585. "geometry_ppname_g": self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  586. "geometry_f_plunge": self.geometry_options_form.geometry_opt_group.fplunge_cb,
  587. "geometry_toolchange": self.geometry_options_form.geometry_opt_group.toolchange_cb,
  588. "geometry_toolchangez": self.geometry_options_form.geometry_opt_group.toolchangez_entry,
  589. "geometry_toolchangexy": self.geometry_options_form.geometry_opt_group.toolchangexy_entry,
  590. "geometry_startz": self.geometry_options_form.geometry_opt_group.gstartz_entry,
  591. "geometry_endz": self.geometry_options_form.geometry_opt_group.gendz_entry,
  592. "geometry_depthperpass": self.geometry_options_form.geometry_opt_group.depthperpass_entry,
  593. "geometry_multidepth": self.geometry_options_form.geometry_opt_group.multidepth_cb,
  594. "geometry_extracut": self.geometry_options_form.geometry_opt_group.extracut_cb,
  595. "cncjob_plot": self.cncjob_options_form.cncjob_gen_group.plot_cb,
  596. "cncjob_tooldia": self.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  597. "cncjob_prepend": self.cncjob_options_form.cncjob_opt_group.prepend_text,
  598. "cncjob_append": self.cncjob_options_form.cncjob_opt_group.append_text,
  599. "tools_ncctools": self.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  600. "tools_nccoverlap": self.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  601. "tools_nccmargin": self.tools_options_form.tools_ncc_group.ncc_margin_entry,
  602. "tools_cutouttooldia": self.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  603. "tools_cutoutmargin": self.tools_options_form.tools_cutout_group.cutout_margin_entry,
  604. "tools_cutoutgapsize": self.tools_options_form.tools_cutout_group.cutout_gap_entry,
  605. "tools_gaps_rect": self.tools_options_form.tools_cutout_group.gaps_radio,
  606. "tools_gaps_ff": self.tools_options_form.tools_cutout_group.gaps_combo,
  607. "tools_painttooldia": self.tools_options_form.tools_paint_group.painttooldia_entry,
  608. "tools_paintoverlap": self.tools_options_form.tools_paint_group.paintoverlap_entry,
  609. "tools_paintmargin": self.tools_options_form.tools_paint_group.paintmargin_entry,
  610. "tools_paintmethod": self.tools_options_form.tools_paint_group.paintmethod_combo,
  611. "tools_selectmethod": self.tools_options_form.tools_paint_group.selectmethod_combo,
  612. "tools_pathconnect": self.tools_options_form.tools_paint_group.pathconnect_cb,
  613. "tools_paintcontour": self.tools_options_form.tools_paint_group.contour_cb,
  614. "tools_2sided_mirror_axis": self.tools_options_form.tools_2sided_group.mirror_axis_radio,
  615. "tools_2sided_axis_loc": self.tools_options_form.tools_2sided_group.axis_location_radio,
  616. "tools_2sided_drilldia": self.tools_options_form.tools_2sided_group.drill_dia_entry
  617. }
  618. for name in list(self.postprocessors.keys()):
  619. self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  620. self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  621. self.options = LoudDict()
  622. self.options.set_change_callback(self.on_options_dict_change)
  623. self.options.update({
  624. "units": "IN",
  625. "global_gridx": 1.0,
  626. "global_gridy": 1.0,
  627. "global_background_timeout": 300000, # Default value is 5 minutes
  628. "global_verbose_error_level": 0, # Shell verbosity:
  629. # 0 = default(python trace only for unknown errors),
  630. # 1 = show trace(show trace allways), 2 = (For the future).
  631. "global_theme": 'standard',
  632. "gerber_plot": True,
  633. "gerber_solid": True,
  634. "gerber_multicolored": False,
  635. "gerber_isotooldia": 0.016,
  636. "gerber_isopasses": 1,
  637. "gerber_isooverlap": 0.15,
  638. "gerber_combine_passes": True,
  639. "gerber_noncoppermargin": 0.0,
  640. "gerber_noncopperrounded": False,
  641. "gerber_bboxmargin": 0.0,
  642. "gerber_bboxrounded": False,
  643. "excellon_plot": True,
  644. "excellon_solid": False,
  645. "excellon_format_upper_in": 2,
  646. "excellon_format_lower_in": 4,
  647. "excellon_format_upper_mm": 3,
  648. "excellon_format_lower_mm": 3,
  649. "excellon_units": 'INCH',
  650. "excellon_optimization_type": 'B',
  651. "excellon_search_time": 3,
  652. "excellon_zeros": "L",
  653. "excellon_drillz": -0.1,
  654. "excellon_travelz": 0.1,
  655. "excellon_feedrate": 3.0,
  656. "excellon_feedrate_rapid": 3.0,
  657. "excellon_spindlespeed": None,
  658. "excellon_dwell": True,
  659. "excellon_dwelltime": 1000,
  660. "excellon_toolchange": False,
  661. "excellon_toolchangez": 1.0,
  662. "excellon_toolchangexy": "0.0, 0.0",
  663. "excellon_tooldia": 0.016,
  664. "excellon_ppname_e": 'default',
  665. "excellon_f_plunge": False,
  666. "excellon_startz": None,
  667. "excellon_endz": 2.0,
  668. "geometry_plot": True,
  669. "geometry_segx": 0.0,
  670. "geometry_segy": 0.0,
  671. "geometry_cutz": -0.002,
  672. "geometry_travelz": 0.1,
  673. "geometry_feedrate": 3.0,
  674. "geometry_feedrate_z": 3.0,
  675. "geometry_feedrate_rapid": 3.0,
  676. "geometry_spindlespeed": None,
  677. "geometry_dwell": True,
  678. "geometry_dwelltime": 1000,
  679. "geometry_cnctooldia": 0.016,
  680. "geometry_toolchange": False,
  681. "geometry_toolchangez": 2.0,
  682. "geometry_toolchangexy": "0.0, 0.0",
  683. "geometry_startz": None,
  684. "geometry_endz": 2.0,
  685. "geometry_ppname_g": "default",
  686. "geometry_f_plunge": False,
  687. "geometry_depthperpass": 0.002,
  688. "geometry_multidepth": False,
  689. "geometry_extracut": False,
  690. "cncjob_plot": True,
  691. "cncjob_tooldia": 0.016,
  692. "cncjob_prepend": "",
  693. "cncjob_append": "",
  694. "tools_ncctools": "1.0, 0.5",
  695. "tools_nccoverlap": 0.4,
  696. "tools_nccmargin": 1,
  697. "tools_cutouttooldia": 0.07,
  698. "tools_cutoutmargin": 0.1,
  699. "tools_cutoutgapsize": 0.15,
  700. "tools_gaps_rect": "4",
  701. "tools_gaps_ff": "8",
  702. "tools_painttooldia": 0.07,
  703. "tools_paintoverlap": 0.15,
  704. "tools_paintmargin": 0.0,
  705. "tools_paintmethod": "seed",
  706. "tools_selectmethod": "single",
  707. "tools_pathconnect": True,
  708. "tools_paintcontour": True,
  709. "tools_2sided_mirror_axis": "X",
  710. "tools_2sided_axis_loc": 'point',
  711. "tools_2sided_drilldia": 1
  712. })
  713. self.options.update(self.defaults) # Copy app defaults to project options
  714. self.gen_form = None
  715. self.ger_form = None
  716. self.exc_form = None
  717. self.geo_form = None
  718. self.cnc_form = None
  719. self.tools_form = None
  720. self.on_options_combo_change(0) # Will show the initial form
  721. ### Define OBJECT COLLECTION ###
  722. self.collection = ObjectCollection(self)
  723. self.ui.project_tab_layout.addWidget(self.collection.view)
  724. ###
  725. self.log.debug("Finished creating Object Collection.")
  726. ### Initialize the color box's color in Preferences -> Global -> Color
  727. # Init Plot Colors
  728. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  729. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  730. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  731. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  732. int(self.defaults['global_plot_fill'][7:9], 16))
  733. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  734. int(self.defaults['global_plot_fill'][7:9], 16))
  735. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  736. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  737. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  738. # Init Left-Right Selection colors
  739. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  740. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  741. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  742. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  743. int(self.defaults['global_sel_fill'][7:9], 16))
  744. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  745. int(self.defaults['global_sel_fill'][7:9], 16))
  746. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  747. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  748. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  749. # Init Right-Left Selection colors
  750. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  751. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  752. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  753. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  754. int(self.defaults['global_sel_fill'][7:9], 16))
  755. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  756. int(self.defaults['global_sel_fill'][7:9], 16))
  757. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  758. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  759. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  760. # Init Draw color and Selection Draw Color
  761. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  762. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  763. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  764. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  765. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  766. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  767. #### End of Data ####
  768. #### Plot Area ####
  769. start_plot_time = time.time() # debug
  770. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  771. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  772. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  773. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  774. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  775. # Keys over plot enabled
  776. self.plotcanvas.vis_connect('key_press', self.on_key_over_plot)
  777. self.plotcanvas.vis_connect('key_release', self.on_key_release_over_plot)
  778. self.ui.splitter.setStretchFactor(1, 2)
  779. # So it can receive key presses
  780. self.plotcanvas.vispy_canvas.native.setFocus()
  781. self.app_cursor = self.plotcanvas.new_cursor()
  782. self.app_cursor.enabled = False
  783. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  784. # depending on from where those tools are called different actions can be done
  785. self.call_source = 'app'
  786. end_plot_time = time.time()
  787. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  788. ### EDITOR section
  789. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  790. self.exc_editor = FlatCAMExcEditor(self)
  791. # start with GRID activated
  792. self.ui.grid_snap_btn.trigger()
  793. self.ui.corner_snap_btn.setVisible(False)
  794. self.ui.snap_magnet.setVisible(False)
  795. self.ui.g_editor_cmenu.setEnabled(False)
  796. self.ui.e_editor_cmenu.setEnabled(False)
  797. #### Adjust tabs width ####
  798. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  799. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  800. self.collection.view.setMinimumWidth(290)
  801. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  802. #### Worker ####
  803. self.workers = WorkerStack()
  804. self.worker_task.connect(self.workers.add_task)
  805. ### Signal handling ###
  806. ## Custom signals
  807. self.inform.connect(self.info)
  808. self.message.connect(self.message_dialog)
  809. self.progress.connect(self.set_progress_bar)
  810. self.object_created.connect(self.on_object_created)
  811. self.object_changed.connect(self.on_object_changed)
  812. self.object_plotted.connect(self.on_object_plotted)
  813. self.plots_updated.connect(self.on_plots_updated)
  814. self.file_opened.connect(self.register_recent)
  815. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  816. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  817. ## Standard signals
  818. # Menu
  819. self.ui.menufilenew.triggered.connect(self.on_file_new_click)
  820. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  821. self.ui.menufileopengerber_follow.triggered.connect(self.on_fileopengerber_follow)
  822. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  823. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  824. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  825. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  826. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  827. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  828. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  829. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  830. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  831. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  832. self.ui.menufileexportexcellon.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=None))
  833. self.ui.menufileexportexcellon_altium.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=True))
  834. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  835. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  836. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  837. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  838. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  839. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  840. self.ui.menueditnew.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  841. self.ui.menueditnewexc.triggered.connect(self.new_excellon_object)
  842. self.ui.menueditedit.triggered.connect(self.object2editor)
  843. self.ui.menueditok.triggered.connect(self.editor2object)
  844. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  845. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  846. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  847. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  848. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  849. self.ui.menueditdelete.triggered.connect(self.on_delete)
  850. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  851. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  852. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  853. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  854. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  855. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  856. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  857. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  858. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  859. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  860. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  861. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  862. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  863. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  864. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  865. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  866. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  867. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  868. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  869. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  870. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  871. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  872. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  873. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  874. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  875. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  876. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  877. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  878. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  879. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  880. self.ui.menuhelp_about.triggered.connect(self.on_about)
  881. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  882. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  883. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  884. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  885. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  886. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  887. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  888. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  889. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  890. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  891. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  892. # Toolbar
  893. #self.ui.file_new_btn.triggered.connect(self.on_file_new)
  894. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  895. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  896. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  897. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  898. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  899. self.ui.replot_btn.triggered.connect(self.plot_all)
  900. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  901. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  902. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  903. self.ui.newgeo_btn.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  904. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  905. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  906. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  907. self.ui.delete_btn.triggered.connect(self.on_delete)
  908. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  909. # Context Menu
  910. self.ui.popmenu_new_geo.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  911. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  912. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  913. self.ui.gridmenu_1.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.05"))
  914. self.ui.gridmenu_2.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.1"))
  915. self.ui.gridmenu_3.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.2"))
  916. self.ui.gridmenu_4.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.5"))
  917. self.ui.gridmenu_5.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("1.0"))
  918. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  919. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  920. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  921. self.ui.draw_move.triggered.connect(self.geo_editor.on_move)
  922. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  923. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  924. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  925. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  926. self.ui.clearplot.triggered.connect(self.clear_plots)
  927. self.ui.replot.triggered.connect(self.plot_all)
  928. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  929. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  930. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  931. self.ui.popmenu_save.triggered.connect(self.editor2object)
  932. self.ui.popmenu_move.triggered.connect(self.obj_move)
  933. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  934. # Preferences Plot Area TAB
  935. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  936. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  937. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  938. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  939. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  940. ###############################
  941. ### GUI PREFERENCES SIGNALS ###
  942. ###############################
  943. self.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  944. self.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(self.on_language_apply)
  945. ###############################
  946. ### GUI PREFERENCES SIGNALS ###
  947. ###############################
  948. # Setting plot colors signals
  949. self.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  950. self.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  951. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  952. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  953. self.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  954. self.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  955. # Setting selection (left - right) colors signals
  956. self.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  957. self.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  958. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  959. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  960. self.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  961. self.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  962. # Setting selection (right - left) colors signals
  963. self.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  964. self.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  965. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  966. self.on_alt_sf_color_spinner)
  967. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  968. self.on_alt_sf_color_slider)
  969. self.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  970. self.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  971. # Setting Editor Draw colors signals
  972. self.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  973. self.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  974. self.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  975. self.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  976. self.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  977. self.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  978. self.general_defaults_form.general_gui_group.theme_combo.currentIndexChanged.connect(self.on_theme)
  979. # Modify G-CODE Plot Area TAB
  980. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  981. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  982. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  983. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  984. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  985. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  986. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  987. # Object list
  988. self.collection.view.activated.connect(self.on_row_activated)
  989. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  990. self.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  991. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  992. self.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  993. self.on_excellon_defaults_button)
  994. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  995. self.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  996. self.on_excellon_options_button)
  997. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  998. self.tool_tab_locked = False
  999. ####################
  1000. ### Other setups ###
  1001. ####################
  1002. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1003. self.setup_obj_classes()
  1004. self.setup_recent_items()
  1005. self.setup_component_editor()
  1006. #############
  1007. ### Shell ###
  1008. #############
  1009. ###
  1010. # Auto-complete KEYWORDS
  1011. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1012. 'aligndrill', 'clear',
  1013. 'aligndrillgrid', 'cncjob', 'cutout', 'cutout_any', 'delete', 'drillcncjob',
  1014. 'export_gcode',
  1015. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1016. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1017. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1018. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1019. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1020. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1021. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1022. ]
  1023. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1024. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1025. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1026. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1027. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1028. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1029. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1030. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1031. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1032. ]
  1033. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  1034. self.shell = FCShell(self, version=self.version)
  1035. self.shell._edit.set_model_data(self.myKeywords)
  1036. self.shell.setWindowIcon(self.ui.app_icon)
  1037. self.shell.setWindowTitle("FlatCAM Shell")
  1038. self.shell.resize(*self.defaults["global_shell_shape"])
  1039. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1040. self.shell.append_output("(Type help to get started)\n\n")
  1041. self.init_tcl()
  1042. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1043. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1044. self.ui.shell_dock.setWidget(self.shell)
  1045. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1046. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1047. QtWidgets.QDockWidget.DockWidgetFloatable |
  1048. QtWidgets.QDockWidget.DockWidgetClosable)
  1049. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1050. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1051. if self.defaults["global_shell_at_startup"]:
  1052. self.ui.shell_dock.show()
  1053. else:
  1054. self.ui.shell_dock.hide()
  1055. #########################
  1056. ### Tools and Plugins ###
  1057. #########################
  1058. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1059. self.install_tools()
  1060. ### System Font Parsing ###
  1061. # self.f_parse = ParseFont(self)
  1062. # self.parse_system_fonts()
  1063. # test if the program was started with a script as parameter
  1064. if self.cmd_line_shellfile:
  1065. try:
  1066. with open(self.cmd_line_shellfile, "r") as myfile:
  1067. cmd_line_shellfile_text = myfile.read()
  1068. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1069. except Exception as ext:
  1070. print("ERROR: ", ext)
  1071. sys.exit(2)
  1072. ###########################
  1073. #### Check for updates ####
  1074. ###########################
  1075. # Separate thread (Not worker)
  1076. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1077. if (self.beta is False or self.beta is None) and \
  1078. self.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1079. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1080. self.thr2 = QtCore.QThread()
  1081. self.worker_task.emit({'fcn': self.version_check,
  1082. 'params': []})
  1083. self.thr2.start()
  1084. ####################################
  1085. #### Variables for global usage ####
  1086. ####################################
  1087. # coordinates for relative position display
  1088. self.rel_point1 = (0, 0)
  1089. self.rel_point2 = (0, 0)
  1090. # variable to store coordinates
  1091. self.pos = (0, 0)
  1092. self.pos_jump = (0, 0)
  1093. # variable to store if there was motion before right mouse button click (panning)
  1094. self.panning_action = False
  1095. # variable to store if a command is active (then the var is not None) and which one it is
  1096. self.command_active = None
  1097. # variable to store the status of moving selection action
  1098. # None value means that it's not an selection action
  1099. # True value = a selection from left to right
  1100. # False value = a selection from right to left
  1101. self.selection_type = None
  1102. # List to store the objects that are currently loaded in FlatCAM
  1103. # This list is updated on each object creation or object delete
  1104. self.all_objects_list = []
  1105. # List to store the objects that are selected
  1106. self.sel_objects_list = []
  1107. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1108. self.key_modifiers = None
  1109. # Variable to hold the status of the axis
  1110. self.toggle_axis = True
  1111. # Variable to store the status of the fullscreen event
  1112. self.toggle_fscreen = False
  1113. self.cursor = None
  1114. # Variable to store the GCODE that was edited
  1115. self.gcode_edited = ""
  1116. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1117. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1118. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1119. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1120. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1121. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1122. 'mpf']
  1123. self.svg_list = ['svg']
  1124. self.dxf_list = ['dxf']
  1125. self.prj_list = ['flatprj']
  1126. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1127. # flag for polygons not cleared
  1128. self.poly_not_cleared = False
  1129. ### Save defaults to factory_defaults.FlatConfig file ###
  1130. ### It's done only once after install #############
  1131. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1132. fac_def_from_file = factory_file.read()
  1133. factory_defaults = json.loads(fac_def_from_file)
  1134. # if the file contain an empty dictionary then save the factory defaults into the file
  1135. if not factory_defaults:
  1136. self.save_factory_defaults(silent=False)
  1137. factory_file.close()
  1138. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1139. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1140. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1141. # Post-GUI initialization: Experimental attempt
  1142. # to perform unit tests on the GUI.
  1143. # if post_gui is not None:
  1144. # post_gui(self)
  1145. App.log.debug("END of constructor. Releasing control.")
  1146. # accept a project file as command line parameter
  1147. # the path/file_name must be enclosed in quotes if it contain spaces
  1148. for argument in App.args:
  1149. if '.FlatPrj' in argument:
  1150. try:
  1151. project_name = str(argument)
  1152. if project_name == "":
  1153. self.inform.emit("Open cancelled.")
  1154. else:
  1155. # self.open_project(project_name)
  1156. run_from_arg = True
  1157. self.worker_task.emit({'fcn': self.open_project,
  1158. 'params': [project_name, run_from_arg]})
  1159. except Exception as e:
  1160. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1161. def defaults_read_form(self):
  1162. for option in self.defaults_form_fields:
  1163. try:
  1164. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1165. except:
  1166. pass
  1167. def defaults_write_form(self):
  1168. for option in self.defaults:
  1169. self.defaults_write_form_field(option)
  1170. # try:
  1171. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1172. # except KeyError:
  1173. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1174. # # TODO: Rethink this?
  1175. # pass
  1176. def defaults_write_form_field(self, field):
  1177. try:
  1178. self.defaults_form_fields[field].set_value(self.defaults[field])
  1179. except KeyError:
  1180. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1181. # TODO: Rethink this?
  1182. pass
  1183. def clear_pool(self):
  1184. self.pool.close()
  1185. self.pool = Pool()
  1186. self.pool_recreated.emit(self.pool)
  1187. gc.collect()
  1188. # the order that the tools are installed is important as they can depend on each other install position
  1189. def install_tools(self):
  1190. self.dblsidedtool = DblSidedTool(self)
  1191. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1192. self.measurement_tool = Measurement(self)
  1193. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1194. self.panelize_tool = Panelize(self)
  1195. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1196. self.film_tool = Film(self)
  1197. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'), separator=True)
  1198. self.move_tool = ToolMove(self)
  1199. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1200. before=self.ui.menueditorigin)
  1201. self.cutout_tool = ToolCutout(self)
  1202. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16.png'), pos=self.ui.menutool,
  1203. before=self.measurement_tool.menuAction)
  1204. self.ncclear_tool = NonCopperClear(self)
  1205. self.ncclear_tool.install(icon=QtGui.QIcon('share/flatcam_icon16.png'), pos=self.ui.menutool,
  1206. before=self.measurement_tool.menuAction, separator=True)
  1207. self.paint_tool = ToolPaint(self)
  1208. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1209. before=self.measurement_tool.menuAction, separator=True)
  1210. self.calculator_tool = ToolCalculator(self)
  1211. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1212. self.transform_tool = ToolTransform(self)
  1213. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1214. self.properties_tool = Properties(self)
  1215. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1216. self.image_tool = ToolImage(self)
  1217. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1218. separator=True)
  1219. self.log.debug("Tools are installed.")
  1220. def init_tools(self):
  1221. # delete the data currently in the Tools Tab and the Tab itself
  1222. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1223. if widget is not None:
  1224. widget.deleteLater()
  1225. self.ui.notebook.removeTab(2)
  1226. # rebuild the Tools Tab
  1227. self.ui.tool_tab = QtWidgets.QWidget()
  1228. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1229. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1230. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1231. self.ui.tool_scroll_area = VerticalScrollArea()
  1232. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1233. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1234. self.install_tools()
  1235. self.log.debug("Tools are initialized.")
  1236. # def parse_system_fonts(self):
  1237. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1238. # 'params': []})
  1239. def object2editor(self):
  1240. """
  1241. Send the current Geometry or Excellon object (if any) into the editor.
  1242. :return: None
  1243. """
  1244. # adjust the visibility of some of the canvas context menu
  1245. self.ui.popmenu_edit.setVisible(False)
  1246. self.ui.popmenu_save.setVisible(True)
  1247. if isinstance(self.collection.get_active(), FlatCAMGeometry):
  1248. edited_object = self.collection.get_active()
  1249. # for now, if the Geometry is MultiGeo do not allow the editing
  1250. if edited_object.multigeo is True:
  1251. self.inform.emit("[warning_notcl]Editing a MultiGeo Geometry is not possible for the moment.")
  1252. return
  1253. self.ui.update_obj_btn.setEnabled(True)
  1254. self.geo_editor.edit_fcgeometry(edited_object)
  1255. self.ui.g_editor_cmenu.setEnabled(True)
  1256. # set call source to the Editor we go into
  1257. self.call_source = 'geo_editor'
  1258. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  1259. sel_tab_widget_list = self.ui.selected_tab.findChildren(QtWidgets.QWidget)
  1260. for w in sel_tab_widget_list:
  1261. w.setEnabled(False)
  1262. elif isinstance(self.collection.get_active(), FlatCAMExcellon):
  1263. self.ui.update_obj_btn.setEnabled(True)
  1264. self.exc_editor.edit_exc_obj(self.collection.get_active())
  1265. self.ui.e_editor_cmenu.setEnabled(True)
  1266. # set call source to the Editor we go into
  1267. self.call_source = 'exc_editor'
  1268. else:
  1269. self.inform.emit("[warning_notcl]Select a Geometry or Excellon Object to edit.")
  1270. return
  1271. # make sure that we can't select another object while in Editor Mode:
  1272. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1273. # delete any selection shape that might be active as they are not relevant in Editor
  1274. self.delete_selection_shape()
  1275. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1276. self.inform.emit("[warning_notcl]Editor is activated ...")
  1277. def editor2object(self):
  1278. """
  1279. Transfers the Geometry or Excellon from the editor to the current object.
  1280. :return: None
  1281. """
  1282. # adjust the visibility of some of the canvas context menu
  1283. self.ui.popmenu_edit.setVisible(True)
  1284. self.ui.popmenu_save.setVisible(False)
  1285. edited_obj = self.collection.get_active()
  1286. obj_type = ""
  1287. if isinstance(edited_obj, FlatCAMGeometry):
  1288. obj_type = "Geometry"
  1289. self.geo_editor.update_fcgeometry(edited_obj)
  1290. self.geo_editor.update_options(edited_obj)
  1291. self.geo_editor.deactivate()
  1292. # edited_obj.on_tool_delete(all=True)
  1293. # edited_obj.on_tool_add(dia=edited_obj.options['cnctooldia'])
  1294. self.ui.corner_snap_btn.setEnabled(False)
  1295. self.ui.update_obj_btn.setEnabled(False)
  1296. self.ui.g_editor_cmenu.setEnabled(False)
  1297. self.ui.e_editor_cmenu.setEnabled(False)
  1298. # update the geo object options so it is including the bounding box values
  1299. try:
  1300. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1301. edited_obj.options['xmin'] = xmin
  1302. edited_obj.options['ymin'] = ymin
  1303. edited_obj.options['xmax'] = xmax
  1304. edited_obj.options['ymax'] = ymax
  1305. except AttributeError:
  1306. self.inform.emit("[warning] Object empty after edit.")
  1307. elif isinstance(edited_obj, FlatCAMExcellon):
  1308. obj_type = "Excellon"
  1309. self.exc_editor.update_exc_obj(edited_obj)
  1310. self.exc_editor.deactivate()
  1311. self.ui.corner_snap_btn.setEnabled(False)
  1312. self.ui.update_obj_btn.setEnabled(False)
  1313. self.ui.g_editor_cmenu.setEnabled(False)
  1314. self.ui.e_editor_cmenu.setEnabled(False)
  1315. else:
  1316. self.inform.emit("[warning_notcl]Select a Geometry or Excellon Object to update.")
  1317. return
  1318. # restore the call_source to app
  1319. self.call_source = 'app'
  1320. edited_obj.plot()
  1321. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1322. self.inform.emit("[success] %s is updated, returning to App..." % obj_type)
  1323. # reset the Object UI to original settings
  1324. # edited_obj.set_ui(edited_obj.ui_type())
  1325. # edited_obj.build_ui()
  1326. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1327. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1328. def get_last_folder(self):
  1329. return self.defaults["global_last_folder"]
  1330. def get_last_save_folder(self):
  1331. return self.defaults["global_last_save_folder"]
  1332. def report_usage(self, resource):
  1333. """
  1334. Increments usage counter for the given resource
  1335. in self.defaults['global_stats'].
  1336. :param resource: Name of the resource.
  1337. :return: None
  1338. """
  1339. if resource in self.defaults['global_stats']:
  1340. self.defaults['global_stats'][resource] += 1
  1341. else:
  1342. self.defaults['global_stats'][resource] = 1
  1343. def init_tcl(self):
  1344. if hasattr(self,'tcl'):
  1345. # self.tcl = None
  1346. # TODO we need to clean non default variables and procedures here
  1347. # new object cannot be used here as it will not remember values created for next passes,
  1348. # because tcl was execudted in old instance of TCL
  1349. pass
  1350. else:
  1351. self.tcl = tk.Tcl()
  1352. self.setup_shell()
  1353. self.log.debug("TCL Shell has been initialized.")
  1354. # TODO: This shouldn't be here.
  1355. class TclErrorException(Exception):
  1356. """
  1357. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1358. """
  1359. pass
  1360. def shell_message(self, msg, show=False, error=False):
  1361. """
  1362. Shows a message on the FlatCAM Shell
  1363. :param msg: Message to display.
  1364. :param show: Opens the shell.
  1365. :param error: Shows the message as an error.
  1366. :return: None
  1367. """
  1368. if show:
  1369. self.ui.shell_dock.show()
  1370. try:
  1371. if error:
  1372. self.shell.append_error(msg + "\n")
  1373. else:
  1374. self.shell.append_output(msg + "\n")
  1375. except AttributeError:
  1376. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1377. def raise_tcl_unknown_error(self, unknownException):
  1378. """
  1379. Raise exception if is different type than TclErrorException
  1380. this is here mainly to show unknown errors inside TCL shell console.
  1381. :param unknownException:
  1382. :return:
  1383. """
  1384. if not isinstance(unknownException, self.TclErrorException):
  1385. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1386. else:
  1387. raise unknownException
  1388. def display_tcl_error(self, error, error_info=None):
  1389. """
  1390. escape bracket [ with \ otherwise there is error
  1391. "ERROR: missing close-bracket" instead of real error
  1392. :param error: it may be text or exception
  1393. :return: None
  1394. """
  1395. if isinstance(error, Exception):
  1396. exc_type, exc_value, exc_traceback = error_info
  1397. if not isinstance(error, self.TclErrorException):
  1398. show_trace = 1
  1399. else:
  1400. show_trace = int(self.defaults['global_verbose_error_level'])
  1401. if show_trace > 0:
  1402. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1403. trc_formated = []
  1404. for a in reversed(trc):
  1405. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1406. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1407. exc_type,
  1408. "\n".join(trc_formated))
  1409. else:
  1410. text = "%s" % error
  1411. else:
  1412. text = error
  1413. text = text.replace('[', '\\[').replace('"', '\\"')
  1414. self.tcl.eval('return -code error "%s"' % text)
  1415. def raise_tcl_error(self, text):
  1416. """
  1417. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1418. :param text: text of error
  1419. :return: raise exception
  1420. """
  1421. self.display_tcl_error(text)
  1422. raise self.TclErrorException(text)
  1423. def exec_command(self, text):
  1424. """
  1425. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1426. Also handles execution in separated threads
  1427. :param text:
  1428. :return: output if there was any
  1429. """
  1430. self.report_usage('exec_command')
  1431. result = self.exec_command_test(text, False)
  1432. #MS: added this method call so the geometry is updated once the TCL
  1433. #command is executed
  1434. self.plot_all()
  1435. return result
  1436. def exec_command_test(self, text, reraise=True):
  1437. """
  1438. Same as exec_command(...) with additional control over exceptions.
  1439. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1440. :param text: Input command
  1441. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1442. :return: Output from the command
  1443. """
  1444. text = str(text)
  1445. try:
  1446. self.shell.open_proccessing() # Disables input box.
  1447. result = self.tcl.eval(str(text))
  1448. if result != 'None':
  1449. self.shell.append_output(result + '\n')
  1450. except tk.TclError as e:
  1451. # This will display more precise answer if something in TCL shell fails
  1452. result = self.tcl.eval("set errorInfo")
  1453. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1454. self.shell.append_error('ERROR: ' + result + '\n')
  1455. # Show error in console and just return or in test raise exception
  1456. if reraise:
  1457. raise e
  1458. finally:
  1459. self.shell.close_proccessing()
  1460. pass
  1461. return result
  1462. # """
  1463. # Code below is unsused. Saved for later.
  1464. # """
  1465. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1466. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1467. # self.log.debug(parts)
  1468. # try:
  1469. # if parts[0] not in commands:
  1470. # self.shell.append_error("Unknown command\n")
  1471. # return
  1472. #
  1473. # #import inspect
  1474. # #inspect.getargspec(someMethod)
  1475. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1476. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1477. # self.shell.append_error(
  1478. # "Command %s takes %d arguments. %d given.\n" %
  1479. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1480. # )
  1481. # return
  1482. #
  1483. # cmdfcn = commands[parts[0]]["fcn"]
  1484. # cmdconv = commands[parts[0]]["converters"]
  1485. # if len(parts) - 1 > 0:
  1486. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1487. # else:
  1488. # retval = cmdfcn()
  1489. # retfcn = commands[parts[0]]["retfcn"]
  1490. # if retval and retfcn(retval):
  1491. # self.shell.append_output(retfcn(retval) + "\n")
  1492. #
  1493. # except Exception as e:
  1494. # #self.shell.append_error(''.join(traceback.format_exc()))
  1495. # #self.shell.append_error("?\n")
  1496. # self.shell.append_error(str(e) + "\n")
  1497. def info(self, msg):
  1498. """
  1499. Informs the user. Normally on the status bar, optionally
  1500. also on the shell.
  1501. :param msg: Text to write.
  1502. :return: None
  1503. """
  1504. # Type of message in brackets at the begining of the message.
  1505. match = re.search("\[([^\]]+)\](.*)", msg)
  1506. if match:
  1507. level = match.group(1)
  1508. msg_ = match.group(2)
  1509. self.ui.fcinfo.set_status(str(msg_), level=level)
  1510. if level == "error" or level == "warning":
  1511. self.shell_message(msg, error=True, show=True)
  1512. elif level == "error_notcl" or level == "warning_notcl":
  1513. self.shell_message(msg, error=True, show=False)
  1514. else:
  1515. self.shell_message(msg, error=False, show=False)
  1516. else:
  1517. self.ui.fcinfo.set_status(str(msg), level="info")
  1518. # make sure that if the message is to clear the infobar with a space
  1519. # is not printed over and over on the shell
  1520. if msg != '':
  1521. self.shell_message(msg)
  1522. def restore_toolbar_view(self):
  1523. tb = self.defaults["global_toolbar_view"]
  1524. if tb & 1:
  1525. self.ui.toolbarfile.setVisible(True)
  1526. else:
  1527. self.ui.toolbarfile.setVisible(False)
  1528. if tb & 2:
  1529. self.ui.toolbargeo.setVisible(True)
  1530. else:
  1531. self.ui.toolbargeo.setVisible(False)
  1532. if tb & 4:
  1533. self.ui.toolbarview.setVisible(True)
  1534. else:
  1535. self.ui.toolbarview.setVisible(False)
  1536. if tb & 8:
  1537. self.ui.toolbartools.setVisible(True)
  1538. else:
  1539. self.ui.toolbartools.setVisible(False)
  1540. if tb & 16:
  1541. self.ui.snap_toolbar.setVisible(True)
  1542. else:
  1543. self.ui.snap_toolbar.setVisible(False)
  1544. def load_defaults(self, filename):
  1545. """
  1546. Loads the aplication's default settings from current_defaults.FlatConfig into
  1547. ``self.defaults``.
  1548. :return: None
  1549. """
  1550. try:
  1551. f = open(self.data_path + "/" + filename + ".FlatConfig")
  1552. options = f.read()
  1553. f.close()
  1554. except IOError:
  1555. self.log.error("Could not load defaults file.")
  1556. self.inform.emit("[error] Could not load defaults file.")
  1557. # in case the defaults file can't be loaded, show all toolbars
  1558. self.defaults["global_toolbar_view"] = 31
  1559. return
  1560. try:
  1561. defaults = json.loads(options)
  1562. except:
  1563. # in case the defaults file can't be loaded, show all toolbars
  1564. self.defaults["global_toolbar_view"] = 31
  1565. e = sys.exc_info()[0]
  1566. App.log.error(str(e))
  1567. self.inform.emit("[error] Failed to parse defaults file.")
  1568. return
  1569. self.defaults.update(defaults)
  1570. log.debug("FlatCAM defaults loaded from: %s" % filename)
  1571. # restore the toolbar view
  1572. self.restore_toolbar_view()
  1573. def on_import_preferences(self):
  1574. """
  1575. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  1576. ``self.defaults``.
  1577. :return: None
  1578. """
  1579. self.report_usage("on_import_preferences")
  1580. App.log.debug("on_import_preferences()")
  1581. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1582. try:
  1583. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences",
  1584. directory=self.data_path, filter=filter)
  1585. except TypeError:
  1586. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences", filter=filter)
  1587. filename = str(filename)
  1588. if filename == "":
  1589. self.inform.emit("[warning_notcl]FlatCAM preferences import cancelled.")
  1590. else:
  1591. try:
  1592. f = open(filename)
  1593. options = f.read()
  1594. f.close()
  1595. except IOError:
  1596. self.log.error("Could not load defaults file.")
  1597. self.inform.emit("[error_notcl] Could not load defaults file.")
  1598. return
  1599. try:
  1600. defaults_from_file = json.loads(options)
  1601. except:
  1602. e = sys.exc_info()[0]
  1603. App.log.error(str(e))
  1604. self.inform.emit("[error_notcl] Failed to parse defaults file.")
  1605. return
  1606. self.defaults.update(defaults_from_file)
  1607. self.inform.emit("[success]Imported Defaults from %s" %filename)
  1608. def on_export_preferences(self):
  1609. self.report_usage("on_export_preferences")
  1610. App.log.debug("on_export_preferences()")
  1611. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1612. try:
  1613. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences",
  1614. directory=self.data_path, filter=filter)
  1615. except TypeError:
  1616. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences", filter=filter)
  1617. filename = str(filename)
  1618. defaults_from_file = {}
  1619. if filename == "":
  1620. self.inform.emit("[warning_notcl]FlatCAM preferences export cancelled.")
  1621. return
  1622. else:
  1623. try:
  1624. f = open(filename, 'w')
  1625. defaults_file_content = f.read()
  1626. f.close()
  1627. except IOError:
  1628. App.log.debug('Creating a new preferences file ...')
  1629. f = open(filename, 'w')
  1630. json.dump({}, f)
  1631. f.close()
  1632. except:
  1633. e = sys.exc_info()[0]
  1634. App.log.error("Could not load defaults file.")
  1635. App.log.error(str(e))
  1636. self.inform.emit("[error_notcl]Could not load defaults file.")
  1637. return
  1638. try:
  1639. defaults_from_file = json.loads(defaults_file_content)
  1640. except:
  1641. App.log.warning("Trying to read an empty Preferences file. Continue.")
  1642. # Update options
  1643. self.defaults_read_form()
  1644. defaults_from_file.update(self.defaults)
  1645. self.propagate_defaults(silent=True)
  1646. # Save update options
  1647. try:
  1648. f = open(filename, "w")
  1649. json.dump(defaults_from_file, f)
  1650. f.close()
  1651. except:
  1652. self.inform.emit("[error_notcl] Failed to write defaults to file.")
  1653. return
  1654. self.inform.emit("[success]Exported Defaults to %s" % filename)
  1655. def on_preferences_open_folder(self):
  1656. if sys.platform == 'win32':
  1657. subprocess.Popen('explorer %s' % self.data_path)
  1658. elif sys.platform == 'darwin':
  1659. os.system('open "%s"' % self.data_path)
  1660. else:
  1661. subprocess.Popen(['xdg-open', self.data_path])
  1662. self.inform.emit("[success]FlatCAM Preferences Folder opened.")
  1663. def save_geometry(self, x, y, width, height, notebook_width):
  1664. self.defaults["global_def_win_x"] = x
  1665. self.defaults["global_def_win_y"] = y
  1666. self.defaults["global_def_win_w"] = width
  1667. self.defaults["global_def_win_h"] = height
  1668. self.defaults["def_notebook_width"] = notebook_width
  1669. self.save_defaults()
  1670. def message_dialog(self, title, message, kind="info"):
  1671. icon = {"info": QtWidgets.QMessageBox.Information,
  1672. "warning": QtWidgets.QMessageBox.Warning,
  1673. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  1674. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  1675. dlg.setText(message)
  1676. dlg.exec_()
  1677. def register_recent(self, kind, filename):
  1678. self.log.debug("register_recent()")
  1679. self.log.debug(" %s" % kind)
  1680. self.log.debug(" %s" % filename)
  1681. record = {'kind': str(kind), 'filename': str(filename)}
  1682. if record in self.recent:
  1683. return
  1684. self.recent.insert(0, record)
  1685. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  1686. self.recent.pop()
  1687. try:
  1688. f = open(self.data_path + '/recent.json', 'w')
  1689. except IOError:
  1690. App.log.error("Failed to open recent items file for writing.")
  1691. self.inform.emit('[error_notcl]Failed to open recent files file for writing.')
  1692. return
  1693. #try:
  1694. json.dump(self.recent, f)
  1695. # except:
  1696. # App.log.error("Failed to write to recent items file.")
  1697. # self.inform.emit('ERROR: Failed to write to recent items file.')
  1698. # f.close()
  1699. f.close()
  1700. # Re-buid the recent items menu
  1701. self.setup_recent_items()
  1702. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  1703. """
  1704. Creates a new specalized FlatCAMObj and attaches it to the application,
  1705. this is, updates the GUI accordingly, any other records and plots it.
  1706. This method is thread-safe.
  1707. Notes:
  1708. * If the name is in use, the self.collection will modify it
  1709. when appending it to the collection. There is no need to handle
  1710. name conflicts here.
  1711. :param kind: The kind of object to create. One of 'gerber',
  1712. 'excellon', 'cncjob' and 'geometry'.
  1713. :type kind: str
  1714. :param name: Name for the object.
  1715. :type name: str
  1716. :param initialize: Function to run after creation of the object
  1717. but before it is attached to the application. The function is
  1718. called with 2 parameters: the new object and the App instance.
  1719. :type initialize: function
  1720. :return: None
  1721. :rtype: None
  1722. """
  1723. App.log.debug("new_object()")
  1724. self.plot = plot
  1725. self.autoselected = autoselected
  1726. t0 = time.time() # Debug
  1727. ## Create object
  1728. classdict = {
  1729. "gerber": FlatCAMGerber,
  1730. "excellon": FlatCAMExcellon,
  1731. "cncjob": FlatCAMCNCjob,
  1732. "geometry": FlatCAMGeometry
  1733. }
  1734. App.log.debug("Calling object constructor...")
  1735. obj = classdict[kind](name)
  1736. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  1737. # Set options from "Project options" form
  1738. self.options_read_form()
  1739. # IMPORTANT
  1740. # The key names in defaults and options dictionary's are not random:
  1741. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  1742. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  1743. # the options from project options form into the self.options. After that, below, depending on the type of
  1744. # object that is created, it will strip the name of the object and the underline (if the original key was
  1745. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  1746. # "toolchange"
  1747. for option in self.options:
  1748. if option.find(kind + "_") == 0:
  1749. oname = option[len(kind) + 1:]
  1750. obj.options[oname] = self.options[option]
  1751. # if kind == 'geometry':
  1752. # obj.tools = {}
  1753. # elif kind == 'cncjob':
  1754. # obj.cnc_tools = {}
  1755. # Initialize as per user request
  1756. # User must take care to implement initialize
  1757. # in a thread-safe way as is is likely that we
  1758. # have been invoked in a separate thread.
  1759. t1 = time.time()
  1760. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  1761. try:
  1762. return_value = initialize(obj, self)
  1763. except Exception as e:
  1764. msg = "[error_notcl] An internal error has ocurred. See shell.\n"
  1765. msg += "Object (%s) failed because: %s \n\n" % (kind, str(e))
  1766. msg += traceback.format_exc()
  1767. self.inform.emit(msg)
  1768. # if str(e) == "Empty Geometry":
  1769. # self.inform.emit("[error_notcl] )
  1770. # else:
  1771. # self.inform.emit("[error] Object (%s) failed because: %s" % (kind, str(e)))
  1772. return "fail"
  1773. t2 = time.time()
  1774. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  1775. if return_value == 'fail':
  1776. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  1777. return "fail"
  1778. # Check units and convert if necessary
  1779. # This condition CAN be true because initialize() can change obj.units
  1780. if self.options["units"].upper() != obj.units.upper():
  1781. self.inform.emit("Converting units to " + self.options["units"] + ".")
  1782. obj.convert_units(self.options["units"])
  1783. t3 = time.time()
  1784. self.log.debug("%f seconds converting units." % (t3 - t2))
  1785. # Create the bounding box for the object and then add the results to the obj.options
  1786. try:
  1787. xmin, ymin, xmax, ymax = obj.bounds()
  1788. obj.options['xmin'] = xmin
  1789. obj.options['ymin'] = ymin
  1790. obj.options['xmax'] = xmax
  1791. obj.options['ymax'] = ymax
  1792. except:
  1793. log.warning("The object has no bounds properties.")
  1794. pass
  1795. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  1796. # Move the object to the main thread and let the app know that it is available.
  1797. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  1798. self.object_created.emit(obj, self.plot, self.autoselected)
  1799. return obj
  1800. def new_excellon_object(self):
  1801. self.new_object('excellon', 'new_e', lambda x, y: None)
  1802. def on_object_created(self, obj, plot, autoselect):
  1803. """
  1804. Event callback for object creation.
  1805. :param obj: The newly created FlatCAM object.
  1806. :return: None
  1807. """
  1808. t0 = time.time() # DEBUG
  1809. self.log.debug("on_object_created()")
  1810. # The Collection might change the name if there is a collision
  1811. self.collection.append(obj)
  1812. # after adding the object to the collection always update the list of objects that are in the collection
  1813. self.all_objects_list = self.collection.get_list()
  1814. self.inform.emit("[success]Object (%s) created: %s" % (obj.kind, obj.options['name']))
  1815. self.new_object_available.emit(obj)
  1816. # update the SHELL auto-completer model with the name of the new object
  1817. self.myKeywords.append(obj.options['name'])
  1818. self.shell._edit.set_model_data(self.myKeywords)
  1819. if autoselect:
  1820. # select the just opened object but deselect the previous ones
  1821. self.collection.set_all_inactive()
  1822. self.collection.set_active(obj.options["name"])
  1823. def worker_task(obj):
  1824. with self.proc_container.new("Plotting"):
  1825. obj.plot()
  1826. t1 = time.time() # DEBUG
  1827. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  1828. self.object_plotted.emit(obj)
  1829. # Send to worker
  1830. # self.worker.add_task(worker_task, [self])
  1831. if plot:
  1832. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  1833. def on_object_changed(self, obj):
  1834. # update the bounding box data from obj.options
  1835. xmin, ymin, xmax, ymax = obj.bounds()
  1836. obj.options['xmin'] = xmin
  1837. obj.options['ymin'] = ymin
  1838. obj.options['xmax'] = xmax
  1839. obj.options['ymax'] = ymax
  1840. log.debug("Object changed, updating the bounding box data on self.options")
  1841. # delete the old selection shape
  1842. self.delete_selection_shape()
  1843. def on_object_plotted(self, obj):
  1844. self.on_zoom_fit(None)
  1845. def options_read_form(self):
  1846. for option in self.options_form_fields:
  1847. self.options[option] = self.options_form_fields[option].get_value()
  1848. def options_write_form(self):
  1849. for option in self.options:
  1850. self.options_write_form_field(option)
  1851. def options_write_form_field(self, field):
  1852. try:
  1853. self.options_form_fields[field].set_value(self.options[field])
  1854. except KeyError:
  1855. # Changed from error to debug. This allows to have data stored
  1856. # which is not user-editable.
  1857. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  1858. pass
  1859. def on_about(self):
  1860. """
  1861. Displays the "about" dialog.
  1862. :return: None
  1863. """
  1864. self.report_usage("on_about")
  1865. version = self.version
  1866. version_date = self.version_date
  1867. beta = self.beta
  1868. class AboutDialog(QtWidgets.QDialog):
  1869. def __init__(self, parent=None):
  1870. QtWidgets.QDialog.__init__(self, parent)
  1871. # Icon and title
  1872. self.setWindowIcon(parent.app_icon)
  1873. self.setWindowTitle("FlatCAM")
  1874. layout1 = QtWidgets.QVBoxLayout()
  1875. self.setLayout(layout1)
  1876. layout2 = QtWidgets.QHBoxLayout()
  1877. layout1.addLayout(layout2)
  1878. logo = QtWidgets.QLabel()
  1879. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  1880. layout2.addWidget(logo, stretch=0)
  1881. title = QtWidgets.QLabel(
  1882. "<font size=8><B>FlatCAM</B></font><BR>"
  1883. "Version %s %s (%s) - %s <BR>"
  1884. "<BR>"
  1885. "2D Computer-Aided Printed Circuit Board<BR>"
  1886. "Manufacturing.<BR>"
  1887. "<BR>"
  1888. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  1889. "<BR>"
  1890. "<B> Main Contributors:</B><BR>"
  1891. "Denis Hayrullin<BR>"
  1892. "Kamil Sopko<BR>"
  1893. "Marius Stanciu<BR>"
  1894. "Matthieu Berthomé<BR>"
  1895. "and many others found "
  1896. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  1897. "<BR>"
  1898. "Development is done "
  1899. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  1900. "DOWNLOAD area "
  1901. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  1902. "" % (version, ('BETA' if beta else ''), version_date, platform.architecture()[0])
  1903. )
  1904. title.setOpenExternalLinks(True)
  1905. layout2.addWidget(title, stretch=1)
  1906. layout3 = QtWidgets.QHBoxLayout()
  1907. layout1.addLayout(layout3)
  1908. layout3.addStretch()
  1909. okbtn = QtWidgets.QPushButton("Close")
  1910. layout3.addWidget(okbtn)
  1911. okbtn.clicked.connect(self.accept)
  1912. AboutDialog(self.ui).exec_()
  1913. def on_file_savedefaults(self):
  1914. """
  1915. Callback for menu item File->Save Defaults. Saves application default options
  1916. ``self.defaults`` to current_defaults.FlatConfig.
  1917. :return: None
  1918. """
  1919. self.save_defaults()
  1920. def on_app_exit(self):
  1921. if self.collection.get_list():
  1922. msgbox = QtWidgets.QMessageBox()
  1923. # msgbox.setText("<B>Save changes ...</B>")
  1924. msgbox.setText("There are files/objects opened in FlatCAM. "
  1925. "\n"
  1926. "Do you want to Save the project?")
  1927. msgbox.setWindowTitle("Save changes")
  1928. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  1929. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  1930. QtWidgets.QMessageBox.Cancel)
  1931. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  1932. response = msgbox.exec_()
  1933. if response == QtWidgets.QMessageBox.Yes:
  1934. self.on_file_saveprojectas(thread=False)
  1935. elif response == QtWidgets.QMessageBox.Cancel:
  1936. return
  1937. self.save_defaults()
  1938. else:
  1939. self.save_defaults()
  1940. log.debug("Application defaults saved ... Exit event.")
  1941. QtWidgets.qApp.quit()
  1942. def save_defaults(self, silent=False):
  1943. """
  1944. Saves application default options
  1945. ``self.defaults`` to current_defaults.FlatConfig.
  1946. :return: None
  1947. """
  1948. self.report_usage("save_defaults")
  1949. # Read options from file
  1950. try:
  1951. f = open(self.data_path + "/current_defaults.FlatConfig")
  1952. defaults_file_content = f.read()
  1953. f.close()
  1954. except:
  1955. e = sys.exc_info()[0]
  1956. App.log.error("Could not load defaults file.")
  1957. App.log.error(str(e))
  1958. self.inform.emit("[error_notcl] Could not load defaults file.")
  1959. return
  1960. try:
  1961. defaults = json.loads(defaults_file_content)
  1962. except:
  1963. e = sys.exc_info()[0]
  1964. App.log.error("Failed to parse defaults file.")
  1965. App.log.error(str(e))
  1966. self.inform.emit("[error_notcl] Failed to parse defaults file.")
  1967. return
  1968. # Update options
  1969. self.defaults_read_form()
  1970. defaults.update(self.defaults)
  1971. self.propagate_defaults(silent=True)
  1972. # Save update options
  1973. try:
  1974. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  1975. json.dump(defaults, f)
  1976. f.close()
  1977. except:
  1978. self.inform.emit("[error_notcl] Failed to write defaults to file.")
  1979. return
  1980. # Save the toolbar view
  1981. tb_status = 0
  1982. if self.ui.toolbarfile.isVisible():
  1983. tb_status += 1
  1984. if self.ui.toolbargeo.isVisible():
  1985. tb_status += 2
  1986. if self.ui.toolbarview.isVisible():
  1987. tb_status += 4
  1988. if self.ui.toolbartools.isVisible():
  1989. tb_status += 8
  1990. if self.ui.snap_toolbar.isVisible():
  1991. tb_status += 16
  1992. self.defaults["global_toolbar_view"] = tb_status
  1993. if not silent:
  1994. self.inform.emit("[success]Defaults saved.")
  1995. def save_factory_defaults(self, silent=False):
  1996. """
  1997. Saves application factory default options
  1998. ``self.defaults`` to factory_defaults.FlatConfig.
  1999. It's a one time job done just after the first install.
  2000. :return: None
  2001. """
  2002. self.report_usage("save_factory_defaults")
  2003. # Read options from file
  2004. try:
  2005. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2006. factory_defaults_file_content = f_f_def.read()
  2007. f_f_def.close()
  2008. except:
  2009. e = sys.exc_info()[0]
  2010. App.log.error("Could not load factory defaults file.")
  2011. App.log.error(str(e))
  2012. self.inform.emit("[error_notcl] Could not load factory defaults file.")
  2013. return
  2014. try:
  2015. factory_defaults = json.loads(factory_defaults_file_content)
  2016. except:
  2017. e = sys.exc_info()[0]
  2018. App.log.error("Failed to parse factory defaults file.")
  2019. App.log.error(str(e))
  2020. self.inform.emit("[error_notcl] Failed to parse factory defaults file.")
  2021. return
  2022. # Update options
  2023. self.defaults_read_form()
  2024. factory_defaults.update(self.defaults)
  2025. self.propagate_defaults(silent=True)
  2026. # Save update options
  2027. try:
  2028. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2029. json.dump(factory_defaults, f_f_def_s)
  2030. f_f_def_s.close()
  2031. except:
  2032. self.inform.emit("[error_notcl] Failed to write factory defaults to file.")
  2033. return
  2034. if silent is False:
  2035. self.inform.emit("Factory defaults saved.")
  2036. def final_save(self):
  2037. if self.collection.get_list():
  2038. msgbox = QtWidgets.QMessageBox()
  2039. # msgbox.setText("<B>Save changes ...</B>")
  2040. msgbox.setText("There are files/objects opened in FlatCAM. "
  2041. "\n"
  2042. "Do you want to Save the project?")
  2043. msgbox.setWindowTitle("Save changes")
  2044. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2045. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2046. QtWidgets.QMessageBox.Cancel)
  2047. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2048. response = msgbox.exec_()
  2049. if response == QtWidgets.QMessageBox.Yes:
  2050. self.on_file_saveprojectas(thread=False)
  2051. elif response == QtWidgets.QMessageBox.Cancel:
  2052. self.should_we_quit = False
  2053. return
  2054. self.save_defaults()
  2055. log.debug("Application defaults saved ... Exit event.")
  2056. def on_toggle_shell(self):
  2057. """
  2058. toggle shell if is visible close it if closed open it
  2059. :return:
  2060. """
  2061. if self.ui.shell_dock.isVisible():
  2062. self.ui.shell_dock.hide()
  2063. else:
  2064. self.ui.shell_dock.show()
  2065. def on_edit_join(self, name=None):
  2066. """
  2067. Callback for Edit->Join. Joins the selected geometry objects into
  2068. a new one.
  2069. :return: None
  2070. """
  2071. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2072. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2073. tooldias = []
  2074. geo_type_list = []
  2075. objs = self.collection.get_selected()
  2076. for obj in objs:
  2077. geo_type_list.append(obj.multigeo)
  2078. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2079. if len(set(geo_type_list)) != 1:
  2080. self.inform.emit("[error] Failed join. The Geometry objects are of different types.\n"
  2081. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2082. "convert from one to another and retry joining \n"
  2083. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2084. "the result may not be what was expected. \n"
  2085. "Check the generated GCODE.")
  2086. return
  2087. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2088. if True in geo_type_list:
  2089. def initialize(obj, app):
  2090. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2091. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2092. for v in obj.tools.values():
  2093. v['data']['name'] = obj_name_multi
  2094. self.new_object("geometry", obj_name_multi, initialize)
  2095. else:
  2096. def initialize(obj, app):
  2097. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2098. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2099. for v in obj.tools.values():
  2100. v['data']['name'] = obj_name_single
  2101. self.new_object("geometry", obj_name_single, initialize)
  2102. def on_edit_join_exc(self):
  2103. """
  2104. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2105. a new one.
  2106. :return: None
  2107. """
  2108. objs = self.collection.get_selected()
  2109. for obj in objs:
  2110. if not isinstance(obj, FlatCAMExcellon):
  2111. self.inform.emit("[error_notcl]Failed. Excellon joining works only on Excellon objects.")
  2112. return
  2113. def initialize(obj, app):
  2114. FlatCAMExcellon.merge(objs, obj)
  2115. self.new_object("excellon", 'Combo_Excellon', initialize)
  2116. def on_edit_join_grb(self):
  2117. """
  2118. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2119. a new one.
  2120. :return: None
  2121. """
  2122. objs = self.collection.get_selected()
  2123. for obj in objs:
  2124. if not isinstance(obj, FlatCAMGerber):
  2125. self.inform.emit("[error_notcl]Failed. Gerber joining works only on Gerber objects.")
  2126. return
  2127. def initialize(obj, app):
  2128. FlatCAMGerber.merge(objs, obj)
  2129. self.new_object("gerber", 'Combo_Gerber', initialize)
  2130. def on_convert_singlegeo_to_multigeo(self):
  2131. obj = self.collection.get_active()
  2132. if obj is None:
  2133. self.inform.emit("[error_notcl]Failed. Select a Geometry Object and try again.")
  2134. return
  2135. if not isinstance(obj, FlatCAMGeometry):
  2136. self.inform.emit("[error_notcl]Expected a FlatCAMGeometry, got %s" % type(obj))
  2137. return
  2138. obj.multigeo = True
  2139. for tooluid, dict_value in obj.tools.items():
  2140. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2141. if not isinstance(obj.solid_geometry, list):
  2142. obj.solid_geometry = [obj.solid_geometry]
  2143. obj.solid_geometry[:] = []
  2144. obj.plot()
  2145. self.inform.emit("[success] A Geometry object was converted to MultiGeo type.")
  2146. def on_convert_multigeo_to_singlegeo(self):
  2147. obj = self.collection.get_active()
  2148. if obj is None:
  2149. self.inform.emit("[error_notcl]Failed. Select a Geometry Object and try again.")
  2150. return
  2151. if not isinstance(obj, FlatCAMGeometry):
  2152. self.inform.emit("[error_notcl]Expected a FlatCAMGeometry, got %s" % type(obj))
  2153. return
  2154. obj.multigeo = False
  2155. total_solid_geometry = []
  2156. for tooluid, dict_value in obj.tools.items():
  2157. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2158. # clear the original geometry
  2159. dict_value['solid_geometry'][:] = []
  2160. obj.solid_geometry = deepcopy(total_solid_geometry)
  2161. obj.plot()
  2162. self.inform.emit("[success] A Geometry object was converted to SingleGeo type.")
  2163. def on_options_dict_change(self, field):
  2164. self.options_write_form_field(field)
  2165. if field == "units":
  2166. self.set_screen_units(self.options['units'])
  2167. def on_defaults_dict_change(self, field):
  2168. self.defaults_write_form_field(field)
  2169. def set_screen_units(self, units):
  2170. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  2171. def on_toggle_units(self):
  2172. """
  2173. Callback for the Units radio-button change in the Options tab.
  2174. Changes the application's default units or the current project's units.
  2175. If changing the project's units, the change propagates to all of
  2176. the objects in the project.
  2177. :return: None
  2178. """
  2179. self.report_usage("on_toggle_units")
  2180. if self.toggle_units_ignore:
  2181. return
  2182. # If option is the same, then ignore
  2183. if self.general_options_form.general_app_group.units_radio.get_value().upper() == self.options["units"].upper():
  2184. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  2185. return
  2186. # Options to scale
  2187. dimensions = ['gerber_isotooldia', 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2188. 'gerber_noncoppermargin', 'gerber_bboxmargin','gerber_isooverlap','tools_nccoverlap',
  2189. 'tools_nccmargin','tools_cutouttooldia','tools_cutoutgapsize',
  2190. 'gerber_noncoppermargin','gerber_bboxmargin',
  2191. 'excellon_drillz', "excellon_toolchangexy",
  2192. 'excellon_travelz', 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2193. 'excellon_tooldia', 'excellon_endz', 'cncjob_tooldia',
  2194. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate', 'geometry_feedrate_rapid',
  2195. 'geometry_cnctooldia', 'tools_painttooldia', 'tools_paintoverlap', 'geometry_toolchangexy',
  2196. 'geometry_toolchangez',
  2197. 'tools_paintmargin', 'geometry_endz', 'geometry_depthperpass', 'global_gridx', 'global_gridy']
  2198. def scale_options(sfactor):
  2199. for dim in dimensions:
  2200. if dim == 'excellon_toolchangexy':
  2201. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2202. coords_xy[0] *= sfactor
  2203. coords_xy[1] *= sfactor
  2204. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2205. elif dim == 'geometry_toolchangexy':
  2206. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2207. coords_xy[0] *= sfactor
  2208. coords_xy[1] *= sfactor
  2209. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2210. else:
  2211. self.options[dim] *= sfactor
  2212. # The scaling factor depending on choice of units.
  2213. factor = 1/25.4
  2214. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2215. factor = 25.4
  2216. # Changing project units. Warn user.
  2217. msgbox = QtWidgets.QMessageBox()
  2218. msgbox.setText("<B>Change project units ...</B>")
  2219. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2220. "properties of all objects to be scaled accordingly. Continue?")
  2221. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2222. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2223. response = msgbox.exec_()
  2224. if response == QtWidgets.QMessageBox.Ok:
  2225. self.options_read_form()
  2226. scale_options(factor)
  2227. self.options_write_form()
  2228. # change this only if the workspace is active
  2229. if self.defaults['global_workspace'] is True:
  2230. self.plotcanvas.draw_workspace()
  2231. # adjust the grid values on the main toolbar
  2232. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2233. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2234. for obj in self.collection.get_list():
  2235. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  2236. obj.convert_units(units)
  2237. # make that the properties stored in the object are also updated
  2238. self.object_changed.emit(obj)
  2239. obj.build_ui()
  2240. current = self.collection.get_active()
  2241. if current is not None:
  2242. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2243. if not isinstance(current, FlatCAMGeometry):
  2244. current.to_form()
  2245. self.plot_all()
  2246. else:
  2247. # Undo toggling
  2248. self.toggle_units_ignore = True
  2249. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2250. self.general_options_form.general_app_group.units_radio.set_value('IN')
  2251. else:
  2252. self.general_options_form.general_app_group.units_radio.set_value('MM')
  2253. self.toggle_units_ignore = False
  2254. self.options_read_form()
  2255. self.inform.emit("Converted units to %s" % self.options["units"])
  2256. #self.ui.units_label.setText("[" + self.options["units"] + "]")
  2257. self.set_screen_units(self.options["units"])
  2258. def on_toggle_units_click(self):
  2259. if self.options["units"] == 'MM':
  2260. self.general_options_form.general_app_group.units_radio.set_value("IN")
  2261. else:
  2262. self.general_options_form.general_app_group.units_radio.set_value("MM")
  2263. self.on_toggle_units()
  2264. def on_language_apply(self):
  2265. # TODO: apply the language
  2266. # app restart section
  2267. pass
  2268. def on_fullscreen(self):
  2269. if self.toggle_fscreen is False:
  2270. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  2271. tb.setVisible(False)
  2272. self.ui.splitter_left.setVisible(False)
  2273. self.toggle_fscreen = True
  2274. else:
  2275. self.restore_toolbar_view()
  2276. self.ui.splitter_left.setVisible(True)
  2277. self.toggle_fscreen = False
  2278. def on_toggle_plotarea(self):
  2279. try:
  2280. name = self.ui.plot_tab_area.widget(0).objectName()
  2281. except AttributeError:
  2282. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  2283. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2284. self.ui.plot_tab_area.protectTab(0)
  2285. return
  2286. if name != 'plotarea':
  2287. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  2288. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2289. self.ui.plot_tab_area.protectTab(0)
  2290. else:
  2291. self.ui.plot_tab_area.closeTab(0)
  2292. def on_toggle_axis(self):
  2293. if self.toggle_axis is False:
  2294. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2295. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2296. self.plotcanvas.redraw()
  2297. self.toggle_axis = True
  2298. else:
  2299. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2300. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2301. self.plotcanvas.redraw()
  2302. self.toggle_axis = False
  2303. def on_toggle_grid(self):
  2304. self.ui.grid_snap_btn.trigger()
  2305. def on_options_combo_change(self, sel):
  2306. """
  2307. Called when the combo box to choose between application defaults and
  2308. project option changes value. The corresponding variables are
  2309. copied to the UI.
  2310. :param sel: The option index that was chosen.
  2311. :return: None
  2312. """
  2313. # combo_sel = self.ui.notebook.combo_options.get_active()
  2314. App.log.debug("Options --> %s" % sel)
  2315. # form = [self.defaults_form, self.options_form][sel]
  2316. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2317. if sel == 0:
  2318. self.gen_form = self.general_defaults_form
  2319. self.ger_form = self.gerber_defaults_form
  2320. self.exc_form = self.excellon_defaults_form
  2321. self.geo_form = self.geometry_defaults_form
  2322. self.cnc_form = self.cncjob_defaults_form
  2323. self.tools_form = self.tools_defaults_form
  2324. elif sel == 1:
  2325. self.gen_form = self.general_options_form
  2326. self.ger_form = self.gerber_options_form
  2327. self.exc_form = self.excellon_options_form
  2328. self.geo_form = self.geometry_options_form
  2329. self.cnc_form = self.cncjob_options_form
  2330. self.tools_form = self.tools_options_form
  2331. else:
  2332. return
  2333. try:
  2334. self.ui.general_scroll_area.takeWidget()
  2335. except:
  2336. self.log.debug("Nothing to remove")
  2337. self.ui.general_scroll_area.setWidget(self.gen_form)
  2338. self.gen_form.show()
  2339. try:
  2340. self.ui.gerber_scroll_area.takeWidget()
  2341. except:
  2342. self.log.debug("Nothing to remove")
  2343. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2344. self.ger_form.show()
  2345. try:
  2346. self.ui.excellon_scroll_area.takeWidget()
  2347. except:
  2348. self.log.debug("Nothing to remove")
  2349. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2350. self.exc_form.show()
  2351. try:
  2352. self.ui.geometry_scroll_area.takeWidget()
  2353. except:
  2354. self.log.debug("Nothing to remove")
  2355. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2356. self.geo_form.show()
  2357. try:
  2358. self.ui.cncjob_scroll_area.takeWidget()
  2359. except:
  2360. self.log.debug("Nothing to remove")
  2361. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2362. self.cnc_form.show()
  2363. try:
  2364. self.ui.tools_scroll_area.takeWidget()
  2365. except:
  2366. self.log.debug("Nothing to remove")
  2367. self.ui.tools_scroll_area.setWidget(self.tools_form)
  2368. self.tools_form.show()
  2369. self.log.debug("Finished GUI form initialization.")
  2370. # self.options2form()
  2371. def on_excellon_defaults_button(self):
  2372. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2373. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2374. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2375. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2376. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2377. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2378. log.debug("Excellon app defaults loaded ...")
  2379. def on_excellon_options_button(self):
  2380. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2381. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2382. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2383. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2384. self.options_form_fields["excellon_zeros"].set_value('L')
  2385. self.options_form_fields["excellon_units"].set_value('INCH')
  2386. log.debug("Excellon options defaults loaded ...")
  2387. # Setting plot colors handlers
  2388. def on_pf_color_entry(self):
  2389. self.defaults['global_plot_fill'] = self.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  2390. self.defaults['global_plot_fill'][7:9]
  2391. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2392. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2393. def on_pf_color_button(self):
  2394. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2395. c_dialog = QtWidgets.QColorDialog()
  2396. plot_fill_color = c_dialog.getColor(initial=current_color)
  2397. if plot_fill_color.isValid() is False:
  2398. return
  2399. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2400. "background-color:%s" % str(plot_fill_color.name()))
  2401. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2402. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  2403. self.defaults['global_plot_fill'] = new_val
  2404. def on_pf_color_spinner(self):
  2405. spinner_value = self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  2406. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  2407. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2408. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2409. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2410. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2411. def on_pf_color_slider(self):
  2412. slider_value = self.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  2413. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  2414. def on_pl_color_entry(self):
  2415. self.defaults['global_plot_line'] = self.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  2416. self.defaults['global_plot_line'][7:9]
  2417. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2418. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2419. def on_pl_color_button(self):
  2420. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2421. # print(current_color)
  2422. c_dialog = QtWidgets.QColorDialog()
  2423. plot_line_color = c_dialog.getColor(initial=current_color)
  2424. if plot_line_color.isValid() is False:
  2425. return
  2426. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2427. "background-color:%s" % str(plot_line_color.name()))
  2428. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2429. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  2430. self.defaults['global_plot_line'] = new_val_line
  2431. # Setting selection colors (left - right) handlers
  2432. def on_sf_color_entry(self):
  2433. self.defaults['global_sel_fill'] = self.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  2434. self.defaults['global_sel_fill'][7:9]
  2435. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2436. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2437. def on_sf_color_button(self):
  2438. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2439. c_dialog = QtWidgets.QColorDialog()
  2440. plot_fill_color = c_dialog.getColor(initial=current_color)
  2441. if plot_fill_color.isValid() is False:
  2442. return
  2443. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2444. "background-color:%s" % str(plot_fill_color.name()))
  2445. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2446. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  2447. self.defaults['global_sel_fill'] = new_val
  2448. def on_sf_color_spinner(self):
  2449. spinner_value = self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  2450. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  2451. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2452. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2453. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2454. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2455. def on_sf_color_slider(self):
  2456. slider_value = self.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  2457. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  2458. def on_sl_color_entry(self):
  2459. self.defaults['global_sel_line'] = self.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  2460. self.defaults['global_sel_line'][7:9]
  2461. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2462. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2463. def on_sl_color_button(self):
  2464. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2465. c_dialog = QtWidgets.QColorDialog()
  2466. plot_line_color = c_dialog.getColor(initial=current_color)
  2467. if plot_line_color.isValid() is False:
  2468. return
  2469. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2470. "background-color:%s" % str(plot_line_color.name()))
  2471. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2472. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  2473. self.defaults['global_sel_line'] = new_val_line
  2474. # Setting selection colors (right - left) handlers
  2475. def on_alt_sf_color_entry(self):
  2476. self.defaults['global_alt_sel_fill'] = self.general_defaults_form.general_gui_group \
  2477. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2478. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2479. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2480. def on_alt_sf_color_button(self):
  2481. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2482. c_dialog = QtWidgets.QColorDialog()
  2483. plot_fill_color = c_dialog.getColor(initial=current_color)
  2484. if plot_fill_color.isValid() is False:
  2485. return
  2486. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2487. "background-color:%s" % str(plot_fill_color.name()))
  2488. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2489. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  2490. self.defaults['global_alt_sel_fill'] = new_val
  2491. def on_alt_sf_color_spinner(self):
  2492. spinner_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  2493. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2494. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2495. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2496. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2497. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2498. def on_alt_sf_color_slider(self):
  2499. slider_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  2500. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2501. def on_alt_sl_color_entry(self):
  2502. self.defaults['global_alt_sel_line'] = self.general_defaults_form.general_gui_group \
  2503. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2504. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2505. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2506. def on_alt_sl_color_button(self):
  2507. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2508. c_dialog = QtWidgets.QColorDialog()
  2509. plot_line_color = c_dialog.getColor(initial=current_color)
  2510. if plot_line_color.isValid() is False:
  2511. return
  2512. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2513. "background-color:%s" % str(plot_line_color.name()))
  2514. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2515. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  2516. self.defaults['global_alt_sel_line'] = new_val_line
  2517. # Setting Editor colors
  2518. def on_draw_color_entry(self):
  2519. self.defaults['global_draw_color'] = self.general_defaults_form.general_gui_group \
  2520. .draw_color_entry.get_value()
  2521. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2522. "background-color:%s" % str(self.defaults['global_draw_color']))
  2523. def on_draw_color_button(self):
  2524. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2525. c_dialog = QtWidgets.QColorDialog()
  2526. draw_color = c_dialog.getColor(initial=current_color)
  2527. if draw_color.isValid() is False:
  2528. return
  2529. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2530. "background-color:%s" % str(draw_color.name()))
  2531. new_val = str(draw_color.name())
  2532. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  2533. self.defaults['global_draw_color'] = new_val
  2534. def on_sel_draw_color_entry(self):
  2535. self.defaults['global_sel_draw_color'] = self.general_defaults_form.general_gui_group \
  2536. .sel_draw_color_entry.get_value()
  2537. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2538. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  2539. def on_sel_draw_color_button(self):
  2540. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  2541. c_dialog = QtWidgets.QColorDialog()
  2542. sel_draw_color = c_dialog.getColor(initial=current_color)
  2543. if sel_draw_color.isValid() is False:
  2544. return
  2545. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2546. "background-color:%s" % str(sel_draw_color.name()))
  2547. new_val_sel = str(sel_draw_color.name())
  2548. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  2549. self.defaults['global_sel_draw_color'] = new_val_sel
  2550. def on_workspace_modified(self):
  2551. self.save_defaults(silent=True)
  2552. self.plotcanvas.draw_workspace()
  2553. def on_workspace(self):
  2554. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2555. self.plotcanvas.restore_workspace()
  2556. else:
  2557. self.plotcanvas.delete_workspace()
  2558. self.save_defaults(silent=True)
  2559. def on_workspace_menu(self):
  2560. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2561. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  2562. else:
  2563. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  2564. self.on_workspace()
  2565. def on_theme(self):
  2566. self.defaults["global_theme"] = self.general_defaults_form.general_gui_group.theme_combo.get_value()
  2567. def on_save_button(self):
  2568. self.save_defaults(silent=False)
  2569. # load the defaults so they are updated into the app
  2570. self.load_defaults(filename='current_defaults')
  2571. # Re-fresh project options
  2572. self.on_options_app2project()
  2573. def handleOpen(self):
  2574. filter_group = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2575. "All Files (*.*)"
  2576. path, _ = QtWidgets.QFileDialog.getOpenFileName(
  2577. caption='Open file', directory=self.get_last_folder(), filter=filter_group)
  2578. if path:
  2579. file = QtCore.QFile(path)
  2580. if file.open(QtCore.QIODevice.ReadOnly):
  2581. stream = QtCore.QTextStream(file)
  2582. self.gcode_edited = stream.readAll()
  2583. self.ui.code_editor.setPlainText(self.gcode_edited)
  2584. file.close()
  2585. def handlePrint(self):
  2586. dialog = QtPrintSupport.QPrintDialog()
  2587. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  2588. self.ui.code_editor.document().print_(dialog.printer())
  2589. def handlePreview(self):
  2590. dialog = QtPrintSupport.QPrintPreviewDialog()
  2591. dialog.paintRequested.connect(self.ui.code_editor.print_)
  2592. dialog.exec_()
  2593. def handleTextChanged(self):
  2594. # enable = not self.ui.code_editor.document().isEmpty()
  2595. # self.ui.buttonPrint.setEnabled(enable)
  2596. # self.ui.buttonPreview.setEnabled(enable)
  2597. pass
  2598. def handleSaveGCode(self):
  2599. _filter_ = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2600. "All Files (*.*)"
  2601. try:
  2602. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  2603. caption="Export G-Code ...", directory=self.defaults["global_last_folder"], filter=_filter_)[0])
  2604. except TypeError:
  2605. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export G-Code ...", filter=_filter_)[0])
  2606. try:
  2607. my_gcode = self.ui.code_editor.toPlainText()
  2608. with open(filename, 'w') as f:
  2609. for line in my_gcode:
  2610. f.write(line)
  2611. except FileNotFoundError:
  2612. self.inform.emit("[WARNING] No such file or directory")
  2613. return
  2614. # Just for adding it to the recent files list.
  2615. self.file_opened.emit("cncjob", filename)
  2616. self.file_saved.emit("cncjob", filename)
  2617. self.inform.emit("Saved to: " + filename)
  2618. def handleFindGCode(self):
  2619. flags = QtGui.QTextDocument.FindCaseSensitively
  2620. text_to_be_found = self.ui.entryFind.get_value()
  2621. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  2622. if r is False:
  2623. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2624. def handleReplaceGCode(self):
  2625. old = self.ui.entryFind.get_value()
  2626. new = self.ui.entryReplace.get_value()
  2627. if self.ui.sel_all_cb.isChecked():
  2628. while True:
  2629. cursor = self.ui.code_editor.textCursor()
  2630. cursor.beginEditBlock()
  2631. flags = QtGui.QTextDocument.FindCaseSensitively
  2632. # self.ui.editor is the QPlainTextEdit
  2633. r = self.ui.code_editor.find(str(old), flags)
  2634. if r:
  2635. qc = self.ui.code_editor.textCursor()
  2636. if qc.hasSelection():
  2637. qc.insertText(new)
  2638. else:
  2639. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2640. break
  2641. # Mark end of undo block
  2642. cursor.endEditBlock()
  2643. else:
  2644. cursor = self.ui.code_editor.textCursor()
  2645. cursor.beginEditBlock()
  2646. qc = self.ui.code_editor.textCursor()
  2647. if qc.hasSelection():
  2648. qc.insertText(new)
  2649. # Mark end of undo block
  2650. cursor.endEditBlock()
  2651. def on_new_geometry(self):
  2652. def initialize(obj, self):
  2653. obj.multitool = False
  2654. self.new_object('geometry', 'new_g', initialize)
  2655. self.plot_all()
  2656. def on_delete(self):
  2657. """
  2658. Delete the currently selected FlatCAMObjs.
  2659. :return: None
  2660. """
  2661. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  2662. # a geometry object before we update it.
  2663. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  2664. if self.collection.get_active():
  2665. self.log.debug("on_delete()")
  2666. self.report_usage("on_delete")
  2667. while (self.collection.get_active()):
  2668. self.delete_first_selected()
  2669. self.inform.emit("Object(s) deleted ...")
  2670. # make sure that the selection shape is deleted, too
  2671. self.delete_selection_shape()
  2672. else:
  2673. self.inform.emit("Failed. No object(s) selected...")
  2674. else:
  2675. self.inform.emit("Save the work in Editor and try again ...")
  2676. def on_set_origin(self):
  2677. """
  2678. Set the origin to the left mouse click position
  2679. :return: None
  2680. """
  2681. #display the message for the user
  2682. #and ask him to click on the desired position
  2683. self.inform.emit('Click to set the origin ...')
  2684. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  2685. def on_jump_to(self):
  2686. """
  2687. Jump to a location by setting the mouse cursor location
  2688. :return:
  2689. """
  2690. dia_box = Dialog_box(title="Jump to Coordinates", label="Enter the coordinates in format X,Y:")
  2691. if dia_box.ok is True:
  2692. try:
  2693. location = eval(dia_box.location)
  2694. if not isinstance(location, tuple):
  2695. self.inform.emit("Wrong coordinates. Enter coordinates in format: X,Y")
  2696. return
  2697. except:
  2698. return
  2699. else:
  2700. return
  2701. self.plotcanvas.fit_center(loc=location)
  2702. cursor = QtGui.QCursor()
  2703. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  2704. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  2705. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  2706. self.inform.emit("Done.")
  2707. def on_copy_object(self):
  2708. def initialize(obj_init, app):
  2709. obj_init.solid_geometry = obj.solid_geometry
  2710. try:
  2711. if obj.tools:
  2712. obj_init.tools = obj.tools
  2713. except Exception as e:
  2714. log.debug("on_copy_object() --> %s" % str(e))
  2715. def initialize_excellon(obj_init, app):
  2716. obj_init.tools = obj.tools
  2717. # drills are offset, so they need to be deep copied
  2718. obj_init.drills = deepcopy(obj.drills)
  2719. # slots are offset, so they need to be deep copied
  2720. obj_init.slots = deepcopy(obj.slots)
  2721. obj_init.create_geometry()
  2722. for obj in self.collection.get_selected():
  2723. obj_name = obj.options["name"]
  2724. try:
  2725. if isinstance(obj, FlatCAMExcellon):
  2726. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  2727. elif isinstance(obj,FlatCAMGerber):
  2728. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  2729. elif isinstance(obj,FlatCAMGeometry):
  2730. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  2731. except Exception as e:
  2732. return "Operation failed: %s" % str(e)
  2733. def on_copy_object2(self, custom_name):
  2734. def initialize_geometry(obj_init, app):
  2735. obj_init.solid_geometry = obj.solid_geometry
  2736. try:
  2737. if obj.tools:
  2738. obj_init.tools = obj.tools
  2739. except Exception as e:
  2740. log.debug("on_copy_object2() --> %s" % str(e))
  2741. def initialize_gerber(obj_init, app):
  2742. obj_init.solid_geometry = obj.solid_geometry
  2743. obj_init.apertures = deepcopy(obj.apertures)
  2744. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  2745. def initialize_excellon(obj_init, app):
  2746. obj_init.tools = obj.tools
  2747. # drills are offset, so they need to be deep copied
  2748. obj_init.drills = deepcopy(obj.drills)
  2749. # slots are offset, so they need to be deep copied
  2750. obj_init.slots = deepcopy(obj.slots)
  2751. obj_init.create_geometry()
  2752. for obj in self.collection.get_selected():
  2753. obj_name = obj.options["name"]
  2754. try:
  2755. if isinstance(obj, FlatCAMExcellon):
  2756. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  2757. elif isinstance(obj,FlatCAMGerber):
  2758. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  2759. elif isinstance(obj,FlatCAMGeometry):
  2760. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  2761. except Exception as e:
  2762. return "Operation failed: %s" % str(e)
  2763. def on_rename_object(self, text):
  2764. named_obj = self.collection.get_active()
  2765. for obj in named_obj:
  2766. if obj is list:
  2767. self.on_rename_object(text)
  2768. else:
  2769. try:
  2770. obj.options['name'] = text
  2771. except:
  2772. log.warning("Could not rename the object in the list")
  2773. def on_copy_object_as_geometry(self):
  2774. def initialize(obj_init, app):
  2775. obj_init.solid_geometry = obj.solid_geometry
  2776. if obj.tools:
  2777. obj_init.tools = obj.tools
  2778. def initialize_excellon(obj, app):
  2779. objs = self.collection.get_selected()
  2780. FlatCAMGeometry.merge(objs, obj)
  2781. for obj in self.collection.get_selected():
  2782. obj_name = obj.options["name"]
  2783. try:
  2784. if isinstance(obj, FlatCAMExcellon):
  2785. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  2786. else:
  2787. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  2788. except Exception as e:
  2789. return "Operation failed: %s" % str(e)
  2790. def on_set_zero_click(self, event):
  2791. #this function will be available only for mouse left click
  2792. pos =[]
  2793. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  2794. if event.button == 1:
  2795. if self.grid_status() == True:
  2796. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2797. else:
  2798. pos = pos_canvas
  2799. x = 0 - pos[0]
  2800. y = 0 - pos[1]
  2801. for obj in self.collection.get_list():
  2802. obj.offset((x,y))
  2803. self.object_changed.emit(obj)
  2804. # obj.plot()
  2805. self.plot_all()
  2806. self.inform.emit('[success] Origin set ...')
  2807. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  2808. def on_selectall(self):
  2809. # delete the possible selection box around a possible selected object
  2810. self.delete_selection_shape()
  2811. for name in self.collection.get_names():
  2812. self.collection.set_active(name)
  2813. curr_sel_obj = self.collection.get_by_name(name)
  2814. # create the selection box around the selected object
  2815. self.draw_selection_shape(curr_sel_obj)
  2816. def on_preferences(self):
  2817. # add the tab if it was closed
  2818. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, "Preferences")
  2819. # delete the absolute and relative position and messages in the infobar
  2820. self.ui.position_label.setText("")
  2821. self.ui.rel_position_label.setText("")
  2822. # Switch plot_area to preferences page
  2823. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  2824. self.ui.show()
  2825. def on_flipy(self):
  2826. obj_list = self.collection.get_selected()
  2827. xminlist = []
  2828. yminlist = []
  2829. xmaxlist = []
  2830. ymaxlist = []
  2831. if not obj_list:
  2832. self.inform.emit("[warning_notcl] No object selected.")
  2833. msg = "Please Select an object to flip!"
  2834. warningbox = QtWidgets.QMessageBox()
  2835. warningbox.setText(msg)
  2836. warningbox.setWindowTitle("Warning ...")
  2837. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2838. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2839. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2840. warningbox.exec_()
  2841. else:
  2842. try:
  2843. # first get a bounding box to fit all
  2844. for obj in obj_list:
  2845. xmin, ymin, xmax, ymax = obj.bounds()
  2846. xminlist.append(xmin)
  2847. yminlist.append(ymin)
  2848. xmaxlist.append(xmax)
  2849. ymaxlist.append(ymax)
  2850. # get the minimum x,y and maximum x,y for all objects selected
  2851. xminimal = min(xminlist)
  2852. yminimal = min(yminlist)
  2853. xmaximal = max(xmaxlist)
  2854. ymaximal = max(ymaxlist)
  2855. px = 0.5 * (xminimal + xmaximal)
  2856. py = 0.5 * (yminimal + ymaximal)
  2857. # execute mirroring
  2858. for obj in obj_list:
  2859. obj.mirror('X', [px, py])
  2860. obj.plot()
  2861. self.object_changed.emit(obj)
  2862. except Exception as e:
  2863. self.inform.emit("[error_notcl] Due of %s, Flip action was not executed." % str(e))
  2864. return
  2865. def on_flipx(self):
  2866. obj_list = self.collection.get_selected()
  2867. xminlist = []
  2868. yminlist = []
  2869. xmaxlist = []
  2870. ymaxlist = []
  2871. if not obj_list:
  2872. self.inform.emit("[warning_notcl] No object selected.")
  2873. msg = "Please Select an object to flip!"
  2874. warningbox = QtWidgets.QMessageBox()
  2875. warningbox.setText(msg)
  2876. warningbox.setWindowTitle("Warning ...")
  2877. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2878. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2879. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2880. warningbox.exec_()
  2881. else:
  2882. try:
  2883. # first get a bounding box to fit all
  2884. for obj in obj_list:
  2885. xmin, ymin, xmax, ymax = obj.bounds()
  2886. xminlist.append(xmin)
  2887. yminlist.append(ymin)
  2888. xmaxlist.append(xmax)
  2889. ymaxlist.append(ymax)
  2890. # get the minimum x,y and maximum x,y for all objects selected
  2891. xminimal = min(xminlist)
  2892. yminimal = min(yminlist)
  2893. xmaximal = max(xmaxlist)
  2894. ymaximal = max(ymaxlist)
  2895. px = 0.5 * (xminimal + xmaximal)
  2896. py = 0.5 * (yminimal + ymaximal)
  2897. # execute mirroring
  2898. for obj in obj_list:
  2899. obj.mirror('Y', [px, py])
  2900. obj.plot()
  2901. self.object_changed.emit(obj)
  2902. except Exception as e:
  2903. self.inform.emit("[error_notcl] Due of %s, Flip action was not executed." % str(e))
  2904. return
  2905. def on_rotate(self, silent=False, preset=None):
  2906. obj_list = self.collection.get_selected()
  2907. xminlist = []
  2908. yminlist = []
  2909. xmaxlist = []
  2910. ymaxlist = []
  2911. if not obj_list:
  2912. self.inform.emit("[warning_notcl] No object selected.")
  2913. msg = "Please Select an object to rotate!"
  2914. warningbox = QtWidgets.QMessageBox()
  2915. warningbox.setText(msg)
  2916. warningbox.setWindowTitle("Warning ...")
  2917. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2918. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2919. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2920. warningbox.exec_()
  2921. else:
  2922. if silent is False:
  2923. rotatebox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2924. min=-360, max=360, decimals=3)
  2925. num, ok = rotatebox.get_value()
  2926. else:
  2927. num = preset
  2928. ok = True
  2929. if ok:
  2930. try:
  2931. # first get a bounding box to fit all
  2932. for obj in obj_list:
  2933. xmin, ymin, xmax, ymax = obj.bounds()
  2934. xminlist.append(xmin)
  2935. yminlist.append(ymin)
  2936. xmaxlist.append(xmax)
  2937. ymaxlist.append(ymax)
  2938. # get the minimum x,y and maximum x,y for all objects selected
  2939. xminimal = min(xminlist)
  2940. yminimal = min(yminlist)
  2941. xmaximal = max(xmaxlist)
  2942. ymaximal = max(ymaxlist)
  2943. px = 0.5 * (xminimal + xmaximal)
  2944. py = 0.5 * (yminimal + ymaximal)
  2945. for sel_obj in obj_list:
  2946. sel_obj.rotate(-num, point=(px, py))
  2947. sel_obj.plot()
  2948. self.object_changed.emit(sel_obj)
  2949. except Exception as e:
  2950. self.inform.emit("[error_notcl] Due of %s, rotation movement was not executed." % str(e))
  2951. return
  2952. def on_skewx(self):
  2953. obj_list = self.collection.get_selected()
  2954. xminlist = []
  2955. yminlist = []
  2956. if not obj_list:
  2957. self.inform.emit("[warning_notcl] No object selected.")
  2958. msg = "Please Select an object to skew/shear!"
  2959. warningbox = QtWidgets.QMessageBox()
  2960. warningbox.setText(msg)
  2961. warningbox.setWindowTitle("Warning ...")
  2962. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2963. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2964. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2965. warningbox.exec_()
  2966. else:
  2967. skewxbox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2968. min=-360, max=360, decimals=3)
  2969. num, ok = skewxbox.get_value()
  2970. if ok:
  2971. # first get a bounding box to fit all
  2972. for obj in obj_list:
  2973. xmin, ymin, xmax, ymax = obj.bounds()
  2974. xminlist.append(xmin)
  2975. yminlist.append(ymin)
  2976. # get the minimum x,y and maximum x,y for all objects selected
  2977. xminimal = min(xminlist)
  2978. yminimal = min(yminlist)
  2979. for obj in obj_list:
  2980. obj.skew(num, 0, point=(xminimal, yminimal))
  2981. obj.plot()
  2982. self.object_changed.emit(obj)
  2983. def on_skewy(self):
  2984. obj_list = self.collection.get_selected()
  2985. xminlist = []
  2986. yminlist = []
  2987. if not obj_list:
  2988. self.inform.emit("[warning_notcl] No object selected.")
  2989. msg = "Please Select an object to skew/shear!"
  2990. warningbox = QtWidgets.QMessageBox()
  2991. warningbox.setText(msg)
  2992. warningbox.setWindowTitle("Warning ...")
  2993. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2994. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2995. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2996. warningbox.exec_()
  2997. else:
  2998. skewybox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2999. min=-360, max=360, decimals=3)
  3000. num, ok = skewybox.get_value()
  3001. if ok:
  3002. # first get a bounding box to fit all
  3003. for obj in obj_list:
  3004. xmin, ymin, xmax, ymax = obj.bounds()
  3005. xminlist.append(xmin)
  3006. yminlist.append(ymin)
  3007. # get the minimum x,y and maximum x,y for all objects selected
  3008. xminimal = min(xminlist)
  3009. yminimal = min(yminlist)
  3010. for obj in obj_list:
  3011. obj.skew(0, num, point=(xminimal, yminimal))
  3012. obj.plot()
  3013. self.object_changed.emit(obj)
  3014. def delete_first_selected(self):
  3015. # Keep this for later
  3016. try:
  3017. name = self.collection.get_active().options["name"]
  3018. except AttributeError:
  3019. self.log.debug("Nothing selected for deletion")
  3020. return
  3021. # Remove plot
  3022. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3023. # self.plotcanvas.auto_adjust_axes()
  3024. # Clear form
  3025. self.setup_component_editor()
  3026. # Remove from dictionary
  3027. self.collection.delete_active()
  3028. self.inform.emit("Object deleted: %s" % name)
  3029. def on_plots_updated(self):
  3030. """
  3031. Callback used to report when the plots have changed.
  3032. Adjust axes and zooms to fit.
  3033. :return: None
  3034. """
  3035. # self.plotcanvas.auto_adjust_axes()
  3036. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  3037. self.on_zoom_fit(None)
  3038. # TODO: Rework toolbar 'clear', 'replot' functions
  3039. def on_toolbar_replot(self):
  3040. """
  3041. Callback for toolbar button. Re-plots all objects.
  3042. :return: None
  3043. """
  3044. self.report_usage("on_toolbar_replot")
  3045. self.log.debug("on_toolbar_replot()")
  3046. try:
  3047. self.collection.get_active().read_form()
  3048. except AttributeError:
  3049. self.log.debug("on_toolbar_replot(): AttributeError")
  3050. pass
  3051. self.plot_all()
  3052. def on_row_activated(self, index):
  3053. if index.isValid():
  3054. if index.internalPointer().parent_item != self.collection.root_item:
  3055. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3056. def grid_status(self):
  3057. if self.ui.grid_snap_btn.isChecked():
  3058. return 1
  3059. else:
  3060. return 0
  3061. def on_key_over_plot(self, event):
  3062. """
  3063. Callback for the key pressed event when the canvas is focused. Keyboard
  3064. shortcuts are handled here. So far, these are the shortcuts:
  3065. ========== ============================================
  3066. Key Action
  3067. ========== ============================================
  3068. '1' Zoom-fit. Fits the axes limits to the data.
  3069. '2' Zoom-out.
  3070. '3' Zoom-in.
  3071. 'ctrl+m' Toggle on-off the measuring tool.
  3072. ========== ============================================
  3073. :param event: Ignored.
  3074. :return: None
  3075. """
  3076. self.key_modifiers = QtWidgets.QApplication.keyboardModifiers()
  3077. if self.key_modifiers == QtCore.Qt.ControlModifier:
  3078. if event.key == 'A':
  3079. self.on_selectall()
  3080. if event.key == 'C':
  3081. self.on_copy_object()
  3082. if event.key == 'E':
  3083. self.on_fileopenexcellon()
  3084. if event.key == 'G':
  3085. self.on_fileopengerber()
  3086. if event.key == 'N':
  3087. self.on_file_new_click()
  3088. if event.key == 'M':
  3089. self.measurement_tool.run()
  3090. if event.key == 'O':
  3091. self.on_file_openproject()
  3092. if event.key == 'S':
  3093. self.on_file_saveproject()
  3094. # Toggle Plot Area
  3095. if event.key == 'F10':
  3096. self.on_toggle_plotarea()
  3097. return
  3098. elif self.key_modifiers == QtCore.Qt.AltModifier:
  3099. # place holder for further shortcut key
  3100. if event.key == '1':
  3101. self.enable_all_plots()
  3102. if event.key == '2':
  3103. self.disable_all_plots()
  3104. if event.key == '3':
  3105. self.disable_other_plots()
  3106. if event.key == 'C':
  3107. self.calculator_tool.run()
  3108. if event.key == 'D':
  3109. self.dblsidedtool.run()
  3110. if event.key == 'L':
  3111. self.film_tool.run()
  3112. if event.key == 'N':
  3113. self.ncclear_tool.run()
  3114. if event.key == 'P':
  3115. self.paint_tool.run()
  3116. if event.key == 'R':
  3117. self.transform_tool.run()
  3118. if event.key == 'U':
  3119. self.cutout_tool.run()
  3120. if event.key == 'Z':
  3121. self.panelize_tool.run()
  3122. if event.key == 'F10':
  3123. self.on_fullscreen()
  3124. return
  3125. elif self.key_modifiers == QtCore.Qt.ShiftModifier:
  3126. # place holder for further shortcut key
  3127. if event.key == 'C':
  3128. self.on_copy_name()
  3129. # Toggle axis
  3130. if event.key == 'G':
  3131. self.on_toggle_axis()
  3132. # Open Preferences Window
  3133. if event.key == 'P':
  3134. self.on_preferences()
  3135. # Rotate Object by 90 degree CCW
  3136. if event.key == 'R':
  3137. self.on_rotate(silent=True, preset=-90)
  3138. # Run a Script
  3139. if event.key == 'S':
  3140. self.on_filerunscript()
  3141. # Toggle Workspace
  3142. if event.key == 'W':
  3143. self.on_workspace_menu()
  3144. # Skew on X axis
  3145. if event.key == 'X':
  3146. self.on_skewx()
  3147. # Skew on Y axis
  3148. if event.key == 'Y':
  3149. self.on_skewy()
  3150. else:
  3151. if event.key == 'F1':
  3152. webbrowser.open(self.manual_url)
  3153. return
  3154. if event.key == 'F2':
  3155. webbrowser.open(self.video_url)
  3156. return
  3157. if event.key == self.defaults['fit_key']: # 1
  3158. self.on_zoom_fit(None)
  3159. return
  3160. if event.key == self.defaults['zoom_out_key']: # 2
  3161. self.plotcanvas.zoom(1 / self.defaults['zoom_ratio'], self.mouse)
  3162. return
  3163. if event.key == self.defaults['zoom_in_key']: # 3
  3164. self.plotcanvas.zoom(self.defaults['zoom_ratio'], self.mouse)
  3165. return
  3166. if event.key == 'Delete':
  3167. self.on_delete()
  3168. return
  3169. if event.key == 'Space':
  3170. if self.collection.get_active() is not None:
  3171. self.collection.get_active().ui.plot_cb.toggle()
  3172. self.delete_selection_shape()
  3173. if event.key == 'E':
  3174. self.object2editor()
  3175. if event.key == self.defaults['grid_toggle_key']: # G
  3176. self.ui.grid_snap_btn.trigger()
  3177. if event.key == 'J':
  3178. self.on_jump_to()
  3179. if event.key == 'L':
  3180. self.new_excellon_object()
  3181. if event.key == 'M':
  3182. self.move_tool.toggle()
  3183. return
  3184. if event.key == 'N':
  3185. self.on_new_geometry()
  3186. if event.key == 'O':
  3187. self.on_set_origin()
  3188. if event.key == 'P':
  3189. self.properties_tool.run()
  3190. if event.key == 'Q':
  3191. self.on_toggle_units_click()
  3192. if event.key == 'R':
  3193. self.on_rotate(silent=True, preset=90)
  3194. if event.key == 'S':
  3195. self.on_toggle_shell()
  3196. if event.key == 'V':
  3197. self.on_zoom_fit(None)
  3198. if event.key == 'X':
  3199. self.on_flipx()
  3200. if event.key == 'Y':
  3201. self.on_flipy()
  3202. if event.key == '`':
  3203. self.on_shortcut_list()
  3204. def on_key_release_over_plot(self, event):
  3205. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3206. if modifiers == QtCore.Qt.ControlModifier:
  3207. return
  3208. elif modifiers == QtCore.Qt.AltModifier:
  3209. # place holder for further shortcut key
  3210. return
  3211. elif modifiers == QtCore.Qt.ShiftModifier:
  3212. # place holder for further shortcut key
  3213. return
  3214. else:
  3215. return
  3216. def on_shortcut_list(self):
  3217. # add the tab if it was closed
  3218. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  3219. # delete the absolute and relative position and messages in the infobar
  3220. self.ui.position_label.setText("")
  3221. self.ui.rel_position_label.setText("")
  3222. # Switch plot_area to preferences page
  3223. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  3224. self.ui.show()
  3225. msg = '''<b>Shortcut list</b><br>
  3226. <br>
  3227. <b>~:</b> Show Shortcut List<br>
  3228. <br>
  3229. <b>1:</b> Zoom Fit<br>
  3230. <b>2:</b> Zoom Out<br>
  3231. <b>3:</b> Zoom In<br>
  3232. <b>A:</b> Draw an Arc (when in Edit Mode)<br>
  3233. <b>C:</b> Copy Geo Item (when in Edit Mode)<br>
  3234. <b>E:</b> Edit Object (if selected)<br>
  3235. <b>G:</b> Grid On/Off<br>
  3236. <b>J:</b> Jump to Coordinates<br>
  3237. <b>L:</b> New Excellon<br>
  3238. <b>M:</b> Move Obj<br>
  3239. <b>M:</b> Move Geo Item (when in Edit Mode)<br>
  3240. <b>N:</b> New Geometry<br>
  3241. <b>N:</b> Draw a Polygon (when in Edit Mode)<br>
  3242. <b>O:</b> Set Origin<br>
  3243. <b>O:</b> Draw a Circle (when in Edit Mode)<br>
  3244. <b>Q:</b> Change Units<br>
  3245. <b>P:</b> Open Properties Tool<br>
  3246. <b>P:</b> Draw a Path (when in Edit Mode)<br>
  3247. <b>R:</b> Rotate by 90 degree CW<br>
  3248. <b>R:</b> Draw Rectangle (when in Edit Mode)<br>
  3249. <b>S:</b> Shell Toggle<br>
  3250. <b>V:</b> View Fit<br>
  3251. <b>X:</b> Flip on X_axis<br>
  3252. <b>Y:</b> Flip on Y_axis<br>
  3253. <br>
  3254. <b>Space:</b> En(Dis)able Obj Plot<br>
  3255. <b>CTRL+A:</b> Select All<br>
  3256. <b>CTRL+C:</b> Copy Obj<br>
  3257. <b>CTRL+E:</b> Open Excellon File<br>
  3258. <b>CTRL+G:</b> Open Gerber File<br>
  3259. <b>CTRL+N:</b> New Project<br>
  3260. <b>CTRL+M:</b> Measurement Tool<br>
  3261. <b>CTRL+O:</b> Open Project<br>
  3262. <b>CTRL+S:</b> Save Project As<br>
  3263. <b>CTRL+S:</b> Save Object and Exit Editor (when in Edit Mode)<br>
  3264. <br>
  3265. <b>SHIFT+C:</b> Copy Obj_Name<br>
  3266. <b>SHIFT+G:</b> Toggle the axis<br>
  3267. <b>SHIFT+P:</b> Open Preferences Window<br>
  3268. <b>SHIFT+R:</b> Rotate by 90 degree CCW<br>
  3269. <b>SHIFT+S:</b> Run a Script<br>
  3270. <b>SHIFT+W:</b> Toggle the workspace<br>
  3271. <b>SHIFT+X:</b> Skew on X axis<br>
  3272. <b>SHIFT+Y:</b> Skew on Y axis<br>
  3273. <br>
  3274. <b>ALT+C:</b> Calculators Tool<br>
  3275. <b>ALT+D:</b> 2-Sided PCB Tool<br>
  3276. <b>ALT+L:</b> Film PCB Tool<br>
  3277. <b>ALT+N:</b> Non-Copper Clearing Tool<br>
  3278. <b>ALT+P:</b> Paint Area Tool<br>
  3279. <b>ALT+R:</b> Transformation Tool<br>
  3280. <b>ALT+U:</b> Cutout PCB Tool<br>
  3281. <b>ALT+F10:</b> Toggle Full Screen<br>
  3282. <br>
  3283. <b>F1:</b> Open Online Manual<br>
  3284. <b>F2:</b> Open Online Tutorials<br>
  3285. <b>Del:</b> Delete Obj
  3286. '''
  3287. helpbox = QtWidgets.QMessageBox()
  3288. helpbox.setText(msg)
  3289. helpbox.setWindowTitle("Help")
  3290. helpbox.setWindowIcon(QtGui.QIcon('share/help.png'))
  3291. helpbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3292. helpbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3293. helpbox.exec_()
  3294. def on_copy_name(self):
  3295. obj = self.collection.get_active()
  3296. try:
  3297. name = obj.options["name"]
  3298. except AttributeError:
  3299. log.debug("on_copy_name() --> No object selected to copy it's name")
  3300. self.inform.emit("[warning_notcl]No object selected to copy it's name")
  3301. return
  3302. self.clipboard.setText(name)
  3303. self.inform.emit("Name copied on clipboard ...")
  3304. def on_mouse_click_over_plot(self, event):
  3305. """
  3306. Callback for the mouse click event over the plot. This event is generated
  3307. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3308. For details, see: http://matplotlib.org/users/event_handling.html
  3309. Default actions are:
  3310. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  3311. :param event: Contains information about the event, like which button
  3312. was clicked, the pixel coordinates and the axes coordinates.
  3313. :return: None
  3314. """
  3315. self.pos = []
  3316. # So it can receive key presses
  3317. self.plotcanvas.vispy_canvas.native.setFocus()
  3318. # Set the mouse button for panning
  3319. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  3320. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3321. if self.grid_status() == True:
  3322. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  3323. self.app_cursor.enabled = True
  3324. else:
  3325. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  3326. self.app_cursor.enabled = False
  3327. try:
  3328. App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  3329. event.button, event.pos[0], event.pos[1], self.pos[0], self.pos[1]))
  3330. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3331. if event.button == 1:
  3332. # Reset here the relative coordinates so there is a new reference on the click position
  3333. if self.rel_point1 is None:
  3334. self.rel_point1 = self.pos
  3335. else:
  3336. self.rel_point2 = copy(self.rel_point1)
  3337. self.rel_point1 = self.pos
  3338. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3339. if modifiers == QtCore.Qt.ShiftModifier:
  3340. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3341. return
  3342. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  3343. # and if it's not selected then it will be selected
  3344. if modifiers == QtCore.Qt.ControlModifier:
  3345. # If there is no active command (self.command_active is None) then we check if we clicked on
  3346. # a object by checking the bounding limits against mouse click position
  3347. if self.command_active is None:
  3348. self.select_objects(key='CTRL')
  3349. else:
  3350. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  3351. # checking the bounding limits against mouse click position
  3352. if self.command_active is None:
  3353. self.select_objects()
  3354. self.on_mouse_move_over_plot(event, origin_click=True)
  3355. except Exception as e:
  3356. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  3357. def on_double_click_over_plot(self, event):
  3358. # make double click work only for the LMB
  3359. if event.button == 1:
  3360. if not self.collection.get_selected():
  3361. pass
  3362. else:
  3363. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3364. #delete the selection shape(S) as it may be in the way
  3365. self.delete_selection_shape()
  3366. def on_mouse_move_over_plot(self, event, origin_click=None):
  3367. """
  3368. Callback for the mouse motion event over the plot. This event is generated
  3369. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3370. For details, see: http://matplotlib.org/users/event_handling.html
  3371. :param event: Contains information about the event.
  3372. :param origin_click
  3373. :return: None
  3374. """
  3375. # So it can receive key presses
  3376. self.plotcanvas.vispy_canvas.native.setFocus()
  3377. self.pos_jump = event.pos
  3378. if origin_click is True:
  3379. pass
  3380. else:
  3381. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3382. if event.button == 2:
  3383. self.panning_action = True
  3384. return
  3385. else:
  3386. self.panning_action = False
  3387. if self.rel_point1 is not None:
  3388. try: # May fail in case mouse not within axes
  3389. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3390. if self.grid_status():
  3391. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3392. self.app_cursor.enabled = True
  3393. # Update cursor
  3394. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3395. else:
  3396. pos = (pos_canvas[0], pos_canvas[1])
  3397. self.app_cursor.enabled = False
  3398. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3399. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3400. dx = pos[0] - self.rel_point1[0]
  3401. dy = pos[1] - self.rel_point1[1]
  3402. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3403. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3404. self.mouse = [pos[0], pos[1]]
  3405. # if the mouse is moved and the LMB is clicked then the action is a selection
  3406. if event.is_dragging == 1 and event.button == 1:
  3407. self.delete_selection_shape()
  3408. if dx < 0:
  3409. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3410. face_color=self.defaults['global_alt_sel_fill'])
  3411. self.selection_type = False
  3412. else:
  3413. self.draw_moving_selection_shape(self.pos, pos)
  3414. self.selection_type = True
  3415. # delete the status message on mouse move
  3416. # self.inform.emit("")
  3417. except:
  3418. self.ui.position_label.setText("")
  3419. self.ui.rel_position_label.setText("")
  3420. self.mouse = None
  3421. def on_mouse_click_release_over_plot(self, event):
  3422. """
  3423. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3424. and has been registered in ''self.__init__()''.
  3425. :param event: contains information about the event.
  3426. :return:
  3427. """
  3428. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3429. if self.grid_status():
  3430. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3431. else:
  3432. pos = (pos_canvas[0], pos_canvas[1])
  3433. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3434. # canvas menu
  3435. try:
  3436. if event.button == 2: # right click
  3437. if self.panning_action is True:
  3438. self.panning_action = False
  3439. else:
  3440. self.cursor = QtGui.QCursor()
  3441. self.ui.popMenu.popup(self.cursor.pos())
  3442. except Exception as e:
  3443. log.warning("Error: %s" % str(e))
  3444. return
  3445. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3446. # selection and then select a type of selection ("enclosing" or "touching")
  3447. try:
  3448. if event.button == 1: # left click
  3449. if self.selection_type is not None:
  3450. self.selection_area_handler(self.pos, pos, self.selection_type)
  3451. self.selection_type = None
  3452. except Exception as e:
  3453. log.warning("Error: %s" % str(e))
  3454. return
  3455. def selection_area_handler(self, start_pos, end_pos, sel_type):
  3456. """
  3457. :param start_pos: mouse position when the selection LMB click was done
  3458. :param end_pos: mouse position when the left mouse button is released
  3459. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3460. :return:
  3461. """
  3462. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3463. self.delete_selection_shape()
  3464. for obj in self.collection.get_list():
  3465. try:
  3466. # select the object(s) only if it is enabled (plotted)
  3467. if obj.options['plot']:
  3468. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']), (obj.options['xmax'], obj.options['ymin']),
  3469. (obj.options['xmax'], obj.options['ymax']), (obj.options['xmin'], obj.options['ymax'])])
  3470. if sel_type is True:
  3471. if poly_obj.within(poly_selection):
  3472. # create the selection box around the selected object
  3473. self.draw_selection_shape(obj)
  3474. self.collection.set_active(obj.options['name'])
  3475. else:
  3476. if poly_selection.intersects(poly_obj):
  3477. # create the selection box around the selected object
  3478. self.draw_selection_shape(obj)
  3479. self.collection.set_active(obj.options['name'])
  3480. except:
  3481. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  3482. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  3483. # In this case poly_obj creation (see above) will fail
  3484. pass
  3485. def select_objects(self, key=None):
  3486. # list where we store the overlapped objects under our mouse left click position
  3487. objects_under_the_click_list = []
  3488. # Populate the list with the overlapped objects on the click position
  3489. curr_x, curr_y = self.pos
  3490. for obj in self.all_objects_list:
  3491. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  3492. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  3493. if obj.options['name'] not in objects_under_the_click_list:
  3494. if obj.options['plot']:
  3495. # add objects to the objects_under_the_click list only if the object is plotted
  3496. # (active and not disabled)
  3497. objects_under_the_click_list.append(obj.options['name'])
  3498. try:
  3499. # If there is no element in the overlapped objects list then make everyone inactive
  3500. # because we selected "nothing"
  3501. if not objects_under_the_click_list:
  3502. self.collection.set_all_inactive()
  3503. # delete the possible selection box around a possible selected object
  3504. self.delete_selection_shape()
  3505. # and as a convenience move the focus to the Project tab because Selected tab is now empty
  3506. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3507. else:
  3508. # case when there is only an object under the click and we toggle it
  3509. if len(objects_under_the_click_list) == 1:
  3510. if self.collection.get_active() is None :
  3511. self.collection.set_active(objects_under_the_click_list[0])
  3512. # create the selection box around the selected object
  3513. curr_sel_obj = self.collection.get_active()
  3514. self.draw_selection_shape(curr_sel_obj)
  3515. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  3516. self.collection.set_all_inactive()
  3517. self.delete_selection_shape()
  3518. self.collection.set_active(objects_under_the_click_list[0])
  3519. # create the selection box around the selected object
  3520. curr_sel_obj = self.collection.get_active()
  3521. self.draw_selection_shape(curr_sel_obj)
  3522. else:
  3523. self.collection.set_all_inactive()
  3524. self.delete_selection_shape()
  3525. else:
  3526. # If there is no selected object
  3527. # make active the first element of the overlapped objects list
  3528. if self.collection.get_active() is None:
  3529. self.collection.set_active(objects_under_the_click_list[0])
  3530. name_sel_obj = self.collection.get_active().options['name']
  3531. # In case that there is a selected object but it is not in the overlapped object list
  3532. # make that object inactive and activate the first element in the overlapped object list
  3533. if name_sel_obj not in objects_under_the_click_list:
  3534. self.collection.set_inactive(name_sel_obj)
  3535. name_sel_obj = objects_under_the_click_list[0]
  3536. self.collection.set_active(name_sel_obj)
  3537. else:
  3538. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  3539. self.collection.set_all_inactive()
  3540. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) % len(objects_under_the_click_list)])
  3541. curr_sel_obj = self.collection.get_active()
  3542. # delete the possible selection box around a possible selected object
  3543. self.delete_selection_shape()
  3544. # create the selection box around the selected object
  3545. self.draw_selection_shape(curr_sel_obj)
  3546. # for obj in self.collection.get_list():
  3547. # obj.plot()
  3548. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  3549. # TODO: on selected objects change the object colors and do not draw the selection box
  3550. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  3551. except Exception as e:
  3552. log.error("[error] Something went bad. %s" % str(e))
  3553. return
  3554. def delete_selection_shape(self):
  3555. self.move_tool.sel_shapes.clear()
  3556. self.move_tool.sel_shapes.redraw()
  3557. def draw_selection_shape(self, sel_obj):
  3558. """
  3559. :param sel_obj: the object for which the selection shape must be drawn
  3560. :return:
  3561. """
  3562. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  3563. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  3564. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  3565. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  3566. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3567. #blue_t = Color('blue')
  3568. blue_t = Color(self.defaults['global_sel_fill'])
  3569. blue_t.alpha = 0.3
  3570. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=self.defaults['global_sel_line'],
  3571. face_color=blue_t, update=True, layer=0, tolerance=None))
  3572. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  3573. """
  3574. :param old_coords: old coordinates
  3575. :param coords: new coordinates
  3576. :return:
  3577. """
  3578. if 'color' in kwargs:
  3579. color = kwargs['color']
  3580. else:
  3581. color = self.defaults['global_sel_line']
  3582. if 'face_color' in kwargs:
  3583. face_color = kwargs['face_color']
  3584. else:
  3585. face_color = self.defaults['global_sel_fill']
  3586. x0, y0 = old_coords
  3587. x1, y1 = coords
  3588. pt1 = (x0, y0)
  3589. pt2 = (x1, y0)
  3590. pt3 = (x1, y1)
  3591. pt4 = (x0, y1)
  3592. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3593. color_t = Color(face_color)
  3594. color_t.alpha = 0.3
  3595. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  3596. layer=0, tolerance=None)
  3597. def on_file_new_click(self):
  3598. if self.collection.get_list():
  3599. msgbox = QtWidgets.QMessageBox()
  3600. # msgbox.setText("<B>Save changes ...</B>")
  3601. msgbox.setText("There are files/objects opened in FlatCAM.\n"
  3602. "Creating a New project will delete them.\n"
  3603. "Do you want to Save the project?")
  3604. msgbox.setWindowTitle("Save changes")
  3605. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3606. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  3607. QtWidgets.QMessageBox.No)
  3608. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3609. response = msgbox.exec_()
  3610. if response == QtWidgets.QMessageBox.Yes:
  3611. self.on_file_saveprojectas()
  3612. elif response == QtWidgets.QMessageBox.Cancel:
  3613. return
  3614. self.on_file_new()
  3615. else:
  3616. self.on_file_new()
  3617. self.inform.emit("[success] New Project created...")
  3618. def on_file_new(self):
  3619. """
  3620. Callback for menu item File->New. Returns the application to its
  3621. startup state. This method is thread-safe.
  3622. :return: None
  3623. """
  3624. self.report_usage("on_file_new")
  3625. # Remove everything from memory
  3626. App.log.debug("on_file_new()")
  3627. # Clear pool
  3628. self.clear_pool()
  3629. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  3630. self.init_tcl()
  3631. self.delete_selection_shape()
  3632. self.collection.delete_all()
  3633. self.setup_component_editor()
  3634. # Clear project filename
  3635. self.project_filename = None
  3636. # Load the application defaults
  3637. self.load_defaults(filename='current_defaults')
  3638. # Re-fresh project options
  3639. self.on_options_app2project()
  3640. # Init Tools
  3641. self.init_tools()
  3642. # take the focus of the Notebook on Project Tab.
  3643. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3644. def obj_properties(self):
  3645. self.properties_tool.run()
  3646. def obj_move(self):
  3647. self.move_tool.run()
  3648. def on_fileopengerber(self):
  3649. """
  3650. File menu callback for opening a Gerber.
  3651. :return: None
  3652. """
  3653. self.report_usage("on_fileopengerber")
  3654. App.log.debug("on_fileopengerber()")
  3655. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3656. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3657. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3658. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3659. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3660. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3661. "Allegro Files (*.art);;" \
  3662. "Mentor Files (*.pho *.gdo);;" \
  3663. "All Files (*.*)"
  3664. try:
  3665. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber",
  3666. directory=self.get_last_folder(), filter=_filter_)
  3667. except TypeError:
  3668. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber", filter=_filter_)
  3669. filenames = [str(filename) for filename in filenames]
  3670. if len(filenames) == 0:
  3671. self.inform.emit("[warning_notcl]Open Gerber cancelled.")
  3672. else:
  3673. for filename in filenames:
  3674. if filename != '':
  3675. self.worker_task.emit({'fcn': self.open_gerber,
  3676. 'params': [filename]})
  3677. def on_fileopengerber_follow(self):
  3678. """
  3679. File menu callback for opening a Gerber.
  3680. :return: None
  3681. """
  3682. self.report_usage("on_fileopengerber_follow")
  3683. App.log.debug("on_fileopengerber_follow()")
  3684. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3685. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3686. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3687. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3688. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3689. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3690. "Allegro Files (*.art);;" \
  3691. "Mentor Files (*.pho *.gdo);;" \
  3692. "All Files (*.*)"
  3693. try:
  3694. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow",
  3695. directory=self.get_last_folder(), filter=_filter_)
  3696. except TypeError:
  3697. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow", filter=_filter_)
  3698. # The Qt methods above will return a QString which can cause problems later.
  3699. # So far json.dump() will fail to serialize it.
  3700. # TODO: Improve the serialization methods and remove this fix.
  3701. filename = str(filename)
  3702. follow = True
  3703. if filename == "":
  3704. self.inform.emit("[warning_notcl]Open Gerber-Follow cancelled.")
  3705. else:
  3706. self.worker_task.emit({'fcn': self.open_gerber,
  3707. 'params': [filename, follow]})
  3708. def on_fileopenexcellon(self):
  3709. """
  3710. File menu callback for opening an Excellon file.
  3711. :return: None
  3712. """
  3713. self.report_usage("on_fileopenexcellon")
  3714. App.log.debug("on_fileopenexcellon()")
  3715. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  3716. "All Files (*.*)"
  3717. try:
  3718. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon",
  3719. directory=self.get_last_folder(), filter=_filter_)
  3720. except TypeError:
  3721. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon", filter=_filter_)
  3722. filenames = [str(filename) for filename in filenames]
  3723. if len(filenames) == 0:
  3724. self.inform.emit("[warning_notcl]Open Excellon cancelled.")
  3725. else:
  3726. for filename in filenames:
  3727. if filename != '':
  3728. self.worker_task.emit({'fcn': self.open_excellon,
  3729. 'params': [filename]})
  3730. def on_fileopengcode(self):
  3731. """
  3732. File menu call back for opening gcode.
  3733. :return: None
  3734. """
  3735. self.report_usage("on_fileopengcode")
  3736. App.log.debug("on_fileopengcode()")
  3737. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  3738. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  3739. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  3740. "All Files (*.*)"
  3741. try:
  3742. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code",
  3743. directory=self.get_last_folder(), filter=_filter_)
  3744. except TypeError:
  3745. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code", filter=_filter_)
  3746. filenames = [str(filename) for filename in filenames]
  3747. if len(filenames) == 0:
  3748. self.inform.emit("[warning_notcl]Open G-Code cancelled.")
  3749. else:
  3750. for filename in filenames:
  3751. if filename != '':
  3752. self.worker_task.emit({'fcn': self.open_gcode,
  3753. 'params': [filename]})
  3754. def on_file_openproject(self):
  3755. """
  3756. File menu callback for opening a project.
  3757. :return: None
  3758. """
  3759. self.report_usage("on_file_openproject")
  3760. App.log.debug("on_file_openproject()")
  3761. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  3762. try:
  3763. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project",
  3764. directory=self.get_last_folder(), filter=_filter_)
  3765. except TypeError:
  3766. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project", filter = _filter_)
  3767. # The Qt methods above will return a QString which can cause problems later.
  3768. # So far json.dump() will fail to serialize it.
  3769. # TODO: Improve the serialization methods and remove this fix.
  3770. filename = str(filename)
  3771. if filename == "":
  3772. self.inform.emit("[warning_notcl]Open Project cancelled.")
  3773. else:
  3774. # self.worker_task.emit({'fcn': self.open_project,
  3775. # 'params': [filename]})
  3776. # The above was failing because open_project() is not
  3777. # thread safe. The new_project()
  3778. self.open_project(filename)
  3779. def on_file_exportsvg(self):
  3780. """
  3781. Callback for menu item File->Export SVG.
  3782. :return: None
  3783. """
  3784. self.report_usage("on_file_exportsvg")
  3785. App.log.debug("on_file_exportsvg()")
  3786. obj = self.collection.get_active()
  3787. if obj is None:
  3788. self.inform.emit("WARNING: No object selected.")
  3789. msg = "Please Select a Geometry object to export"
  3790. msgbox = QtWidgets.QMessageBox()
  3791. msgbox.setInformativeText(msg)
  3792. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3793. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3794. msgbox.exec_()
  3795. return
  3796. # Check for more compatible types and add as required
  3797. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  3798. and not isinstance(obj, FlatCAMExcellon)):
  3799. msg = "[error_notcl] Only Geometry, Gerber and CNCJob objects can be used."
  3800. msgbox = QtWidgets.QMessageBox()
  3801. msgbox.setInformativeText(msg)
  3802. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3803. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3804. msgbox.exec_()
  3805. return
  3806. name = self.collection.get_active().options["name"]
  3807. filter = "SVG File (*.svg);;All Files (*.*)"
  3808. try:
  3809. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG",
  3810. directory=self.get_last_save_folder(), filter=filter)
  3811. except TypeError:
  3812. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG", filter=filter)
  3813. filename = str(filename)
  3814. if filename == "":
  3815. self.inform.emit("[warning_notcl]Export SVG cancelled.")
  3816. return
  3817. else:
  3818. self.export_svg(name, filename)
  3819. self.file_saved.emit("SVG", filename)
  3820. def on_file_exportpng(self):
  3821. self.report_usage("on_file_exportpng")
  3822. App.log.debug("on_file_exportpng()")
  3823. image = _screenshot()
  3824. data = np.asarray(image)
  3825. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  3826. self.inform.emit('[[warning_notcl]] Data must be a 3D array with last dimension 3 or 4')
  3827. return
  3828. filter = "PNG File (*.png);;All Files (*.*)"
  3829. try:
  3830. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image",
  3831. directory=self.get_last_save_folder(), filter=filter)
  3832. except TypeError:
  3833. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image", filter=filter)
  3834. filename = str(filename)
  3835. if filename == "":
  3836. self.inform.emit("Export PNG cancelled.")
  3837. return
  3838. else:
  3839. write_png(filename, data)
  3840. self.file_saved.emit("png", filename)
  3841. def on_file_exportexcellon(self, altium_format=None):
  3842. """
  3843. Callback for menu item File->Export SVG.
  3844. :return: None
  3845. """
  3846. self.report_usage("on_file_exportexcellon")
  3847. App.log.debug("on_file_exportexcellon()")
  3848. obj = self.collection.get_active()
  3849. if obj is None:
  3850. self.inform.emit("[warning_notcl] No object selected.")
  3851. msg = "Please Select an Excellon object to export"
  3852. msgbox = QtWidgets.QMessageBox()
  3853. msgbox.setInformativeText(msg)
  3854. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3855. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3856. msgbox.exec_()
  3857. return
  3858. # Check for more compatible types and add as required
  3859. if not isinstance(obj, FlatCAMExcellon):
  3860. msg = "[warning_notcl] Only Excellon objects can be used."
  3861. msgbox = QtWidgets.QMessageBox()
  3862. msgbox.setInformativeText(msg)
  3863. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3864. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3865. msgbox.exec_()
  3866. return
  3867. name = self.collection.get_active().options["name"]
  3868. filter = "Excellon File (*.drl);;Excellon File (*.txt);;All Files (*.*)"
  3869. try:
  3870. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon",
  3871. directory=self.get_last_save_folder(), filter=filter)
  3872. except TypeError:
  3873. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon", filter=filter)
  3874. filename = str(filename)
  3875. if filename == "":
  3876. self.inform.emit("[warning_notcl]Export Excellon cancelled.")
  3877. return
  3878. else:
  3879. if altium_format == None:
  3880. self.export_excellon(name, filename)
  3881. self.file_saved.emit("Excellon", filename)
  3882. else:
  3883. self.export_excellon(name, filename, altium_format=True)
  3884. self.file_saved.emit("Excellon", filename)
  3885. def on_file_exportdxf(self):
  3886. """
  3887. Callback for menu item File->Export DXF.
  3888. :return: None
  3889. """
  3890. self.report_usage("on_file_exportdxf")
  3891. App.log.debug("on_file_exportdxf()")
  3892. obj = self.collection.get_active()
  3893. if obj is None:
  3894. self.inform.emit("W[warning_notcl] No object selected.")
  3895. msg = "Please Select a Geometry object to export"
  3896. msgbox = QtWidgets.QMessageBox()
  3897. msgbox.setInformativeText(msg)
  3898. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3899. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3900. msgbox.exec_()
  3901. return
  3902. # Check for more compatible types and add as required
  3903. if not isinstance(obj, FlatCAMGeometry):
  3904. msg = "[error_notcl] Only Geometry objects can be used."
  3905. msgbox = QtWidgets.QMessageBox()
  3906. msgbox.setInformativeText(msg)
  3907. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3908. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3909. msgbox.exec_()
  3910. return
  3911. name = self.collection.get_active().options["name"]
  3912. filter = "DXF File (*.DXF);;All Files (*.*)"
  3913. try:
  3914. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF",
  3915. directory=self.get_last_save_folder(), filter=filter)
  3916. except TypeError:
  3917. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF", filter=filter)
  3918. filename = str(filename)
  3919. if filename == "":
  3920. self.inform.emit("[warning_notcl]Export DXF cancelled.")
  3921. return
  3922. else:
  3923. self.export_dxf(name, filename)
  3924. self.file_saved.emit("DXF", filename)
  3925. def on_file_importsvg(self, type_of_obj):
  3926. """
  3927. Callback for menu item File->Import SVG.
  3928. :param type_of_obj: to import the SVG as Geometry or as Gerber
  3929. :type type_of_obj: str
  3930. :return: None
  3931. """
  3932. self.report_usage("on_file_importsvg")
  3933. App.log.debug("on_file_importsvg()")
  3934. filter = "SVG File (*.svg);;All Files (*.*)"
  3935. try:
  3936. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG",
  3937. directory=self.get_last_folder(), filter=filter)
  3938. except TypeError:
  3939. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG", filter=filter)
  3940. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  3941. type_of_obj = "geometry"
  3942. filenames = [str(filename) for filename in filenames]
  3943. if len(filenames) == 0:
  3944. self.inform.emit("[warning_notcl]Open SVG cancelled.")
  3945. else:
  3946. for filename in filenames:
  3947. if filename != '':
  3948. self.worker_task.emit({'fcn': self.import_svg,
  3949. 'params': [filename, type_of_obj]})
  3950. def on_file_importdxf(self, type_of_obj):
  3951. """
  3952. Callback for menu item File->Import DXF.
  3953. :param type_of_obj: to import the DXF as Geometry or as Gerber
  3954. :type type_of_obj: str
  3955. :return: None
  3956. """
  3957. self.report_usage("on_file_importdxf")
  3958. App.log.debug("on_file_importdxf()")
  3959. filter = "DXF File (*.DXF);;All Files (*.*)"
  3960. try:
  3961. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF",
  3962. directory=self.get_last_folder(), filter=filter)
  3963. except TypeError:
  3964. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF", filter=filter)
  3965. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  3966. type_of_obj = "geometry"
  3967. filenames = [str(filename) for filename in filenames]
  3968. if len(filenames) == 0:
  3969. self.inform.emit("[warning_notcl]Open DXF cancelled.")
  3970. else:
  3971. for filename in filenames:
  3972. if filename != '':
  3973. self.worker_task.emit({'fcn': self.import_dxf,
  3974. 'params': [filename, type_of_obj]})
  3975. def on_filerunscript(self):
  3976. """
  3977. File menu callback for loading and running a TCL script.
  3978. :return: None
  3979. """
  3980. self.report_usage("on_filerunscript")
  3981. App.log.debug("on_file_runscript()")
  3982. _filter_ = "TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  3983. try:
  3984. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script",
  3985. directory=self.get_last_folder(), filter=_filter_)
  3986. except TypeError:
  3987. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script", filter=_filter_)
  3988. # The Qt methods above will return a QString which can cause problems later.
  3989. # So far json.dump() will fail to serialize it.
  3990. # TODO: Improve the serialization methods and remove this fix.
  3991. filename = str(filename)
  3992. if filename == "":
  3993. self.inform.emit("[warning_notcl]Open TCL script cancelled.")
  3994. else:
  3995. try:
  3996. with open(filename, "r") as tcl_script:
  3997. cmd_line_shellfile_content = tcl_script.read()
  3998. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  3999. except Exception as ext:
  4000. print("ERROR: ", ext)
  4001. sys.exit(2)
  4002. def on_file_saveproject(self):
  4003. """
  4004. Callback for menu item File->Save Project. Saves the project to
  4005. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  4006. if set to None. The project is saved by calling ``self.save_project()``.
  4007. :return: None
  4008. """
  4009. self.report_usage("on_file_saveproject")
  4010. if self.project_filename is None:
  4011. self.on_file_saveprojectas()
  4012. else:
  4013. self.worker_task.emit({'fcn': self.save_project,
  4014. 'params': [self.project_filename]})
  4015. # self.save_project(self.project_filename)
  4016. self.file_opened.emit("project", self.project_filename)
  4017. self.file_saved.emit("project", self.project_filename)
  4018. def on_file_saveprojectas(self, make_copy=False, thread=True):
  4019. """
  4020. Callback for menu item File->Save Project As... Opens a file
  4021. chooser and saves the project to the given file via
  4022. ``self.save_project()``.
  4023. :return: None
  4024. """
  4025. self.report_usage("on_file_saveprojectas")
  4026. filter = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  4027. try:
  4028. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...",
  4029. directory=self.get_last_save_folder(), filter=filter)
  4030. except TypeError:
  4031. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...", filter=filter)
  4032. filename = str(filename)
  4033. if filename == '':
  4034. self.inform.emit("[warning_notcl]Save Project cancelled.")
  4035. return
  4036. try:
  4037. f = open(filename, 'r')
  4038. f.close()
  4039. exists = True
  4040. except IOError:
  4041. exists = False
  4042. msg = "File exists. Overwrite?"
  4043. if exists:
  4044. msgbox = QtWidgets.QMessageBox()
  4045. msgbox.setInformativeText(msg)
  4046. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel |QtWidgets.QMessageBox.Ok)
  4047. msgbox.setDefaultButton(QtWidgets.QMessageBox.Cancel)
  4048. result = msgbox.exec_()
  4049. if result ==QtWidgets.QMessageBox.Cancel:
  4050. return
  4051. if thread is True:
  4052. self.worker_task.emit({'fcn': self.save_project,
  4053. 'params': [filename]})
  4054. else:
  4055. self.save_project(filename)
  4056. # self.save_project(filename)
  4057. self.file_opened.emit("project", filename)
  4058. self.file_saved.emit("project", filename)
  4059. if not make_copy:
  4060. self.project_filename = filename
  4061. def export_svg(self, obj_name, filename, scale_factor=0.00):
  4062. """
  4063. Exports a Geometry Object to an SVG file.
  4064. :param filename: Path to the SVG file to save to.
  4065. :return:
  4066. """
  4067. if filename is None:
  4068. filename = self.defaults["global_last_save_folder"]
  4069. self.log.debug("export_svg()")
  4070. try:
  4071. obj = self.collection.get_by_name(str(obj_name))
  4072. except:
  4073. # TODO: The return behavior has not been established... should raise exception?
  4074. return "Could not retrieve object: %s" % obj_name
  4075. with self.proc_container.new("Exporting SVG") as proc:
  4076. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4077. # Determine bounding area for svg export
  4078. bounds = obj.bounds()
  4079. size = obj.size()
  4080. # Convert everything to strings for use in the xml doc
  4081. svgwidth = str(size[0])
  4082. svgheight = str(size[1])
  4083. minx = str(bounds[0])
  4084. miny = str(bounds[1] - size[1])
  4085. uom = obj.units.lower()
  4086. # Add a SVG Header and footer to the svg output from shapely
  4087. # The transform flips the Y Axis so that everything renders
  4088. # properly within svg apps such as inkscape
  4089. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4090. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4091. svg_header += 'width="' + svgwidth + uom + '" '
  4092. svg_header += 'height="' + svgheight + uom + '" '
  4093. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  4094. svg_header += '<g transform="scale(1,-1)">'
  4095. svg_footer = '</g> </svg>'
  4096. svg_elem = svg_header + exported_svg + svg_footer
  4097. # Parse the xml through a xml parser just to add line feeds
  4098. # and to make it look more pretty for the output
  4099. svgcode = parse_xml_string(svg_elem)
  4100. with open(filename, 'w') as fp:
  4101. fp.write(svgcode.toprettyxml())
  4102. self.file_saved.emit("SVG", filename)
  4103. self.inform.emit("[success] SVG file exported to " + filename)
  4104. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  4105. """
  4106. Exports a Geometry Object to an SVG file in negative.
  4107. :param filename: Path to the SVG file to save to.
  4108. :param: use_thread: If True use threads
  4109. :type: Bool
  4110. :return:
  4111. """
  4112. if filename is None:
  4113. filename = self.defaults["global_last_save_folder"]
  4114. self.log.debug("export_svg() negative")
  4115. try:
  4116. obj = self.collection.get_by_name(str(obj_name))
  4117. except:
  4118. # TODO: The return behavior has not been established... should raise exception?
  4119. return "Could not retrieve object: %s" % obj_name
  4120. try:
  4121. box = self.collection.get_by_name(str(box_name))
  4122. except:
  4123. # TODO: The return behavior has not been established... should raise exception?
  4124. return "Could not retrieve object: %s" % box_name
  4125. if box is None:
  4126. self.inform.emit("[warning_notcl]No object Box. Using instead %s" % obj)
  4127. box = obj
  4128. def make_negative_film():
  4129. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4130. self.progress.emit(40)
  4131. # Determine bounding area for svg export
  4132. bounds = box.bounds()
  4133. size = box.size()
  4134. uom = obj.units.lower()
  4135. # Convert everything to strings for use in the xml doc
  4136. svgwidth = str(size[0] + (2 * boundary))
  4137. svgheight = str(size[1] + (2 * boundary))
  4138. minx = str(bounds[0] - boundary)
  4139. miny = str(bounds[1] + boundary + size[1])
  4140. miny_rect = str(bounds[1] - boundary)
  4141. # Add a SVG Header and footer to the svg output from shapely
  4142. # The transform flips the Y Axis so that everything renders
  4143. # properly within svg apps such as inkscape
  4144. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4145. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4146. svg_header += 'width="' + svgwidth + uom + '" '
  4147. svg_header += 'height="' + svgheight + uom + '" '
  4148. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4149. svg_header += '>'
  4150. svg_header += '<g transform="scale(1,-1)">'
  4151. svg_footer = '</g> </svg>'
  4152. self.progress.emit(60)
  4153. # Change the attributes of the exported SVG
  4154. # We don't need stroke-width - wrong, we do when we have lines with certain width
  4155. # We set opacity to maximum
  4156. # We set the color to WHITE
  4157. root = ET.fromstring(exported_svg)
  4158. for child in root:
  4159. child.set('fill', '#FFFFFF')
  4160. child.set('opacity', '1.0')
  4161. child.set('stroke', '#FFFFFF')
  4162. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  4163. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  4164. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  4165. first_svg_elem_tag = 'rect'
  4166. first_svg_elem_attribs = {
  4167. 'x': minx,
  4168. 'y': miny_rect,
  4169. 'width': svgwidth,
  4170. 'height': svgheight,
  4171. 'id': 'neg_rect',
  4172. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  4173. }
  4174. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  4175. exported_svg = ET.tostring(root)
  4176. svg_elem = svg_header + str(exported_svg) + svg_footer
  4177. self.progress.emit(80)
  4178. # Parse the xml through a xml parser just to add line feeds
  4179. # and to make it look more pretty for the output
  4180. doc = parse_xml_string(svg_elem)
  4181. with open(filename, 'w') as fp:
  4182. fp.write(doc.toprettyxml())
  4183. self.progress.emit(100)
  4184. self.file_saved.emit("SVG", filename)
  4185. self.inform.emit("[success] SVG file exported to " + filename)
  4186. if use_thread is True:
  4187. proc = self.proc_container.new("Generating Film ... Please wait.")
  4188. def job_thread_film(app_obj):
  4189. try:
  4190. make_negative_film()
  4191. except Exception as e:
  4192. proc.done()
  4193. return
  4194. proc.done()
  4195. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4196. else:
  4197. make_negative_film()
  4198. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  4199. """
  4200. Exports a Geometry Object to an SVG file in negative.
  4201. :param filename: Path to the SVG file to save to.
  4202. :param: use_thread: If True use threads
  4203. :type: Bool
  4204. :return:
  4205. """
  4206. if filename is None:
  4207. filename = self.defaults["global_last_save_folder"]
  4208. self.log.debug("export_svg() black")
  4209. try:
  4210. obj = self.collection.get_by_name(str(obj_name))
  4211. except:
  4212. # TODO: The return behavior has not been established... should raise exception?
  4213. return "Could not retrieve object: %s" % obj_name
  4214. try:
  4215. box = self.collection.get_by_name(str(box_name))
  4216. except:
  4217. # TODO: The return behavior has not been established... should raise exception?
  4218. return "Could not retrieve object: %s" % box_name
  4219. if box is None:
  4220. self.inform.emit("[warning_notcl]No object Box. Using instead %s" % obj)
  4221. box = obj
  4222. def make_black_film():
  4223. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4224. self.progress.emit(40)
  4225. # Change the attributes of the exported SVG
  4226. # We don't need stroke-width
  4227. # We set opacity to maximum
  4228. # We set the colour to WHITE
  4229. root = ET.fromstring(exported_svg)
  4230. for child in root:
  4231. child.set('fill', '#000000')
  4232. child.set('opacity', '1.0')
  4233. child.set('stroke', '#000000')
  4234. exported_svg = ET.tostring(root)
  4235. # Determine bounding area for svg export
  4236. bounds = box.bounds()
  4237. size = box.size()
  4238. # This contain the measure units
  4239. uom = obj.units.lower()
  4240. # Define a boundary around SVG of about 1.0mm (~39mils)
  4241. if uom in "mm":
  4242. boundary = 1.0
  4243. else:
  4244. boundary = 0.0393701
  4245. self.progress.emit(80)
  4246. # Convert everything to strings for use in the xml doc
  4247. svgwidth = str(size[0] + (2 * boundary))
  4248. svgheight = str(size[1] + (2 * boundary))
  4249. minx = str(bounds[0] - boundary)
  4250. miny = str(bounds[1] + boundary + size[1])
  4251. self.log.debug(minx)
  4252. self.log.debug(miny)
  4253. # Add a SVG Header and footer to the svg output from shapely
  4254. # The transform flips the Y Axis so that everything renders
  4255. # properly within svg apps such as inkscape
  4256. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4257. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4258. svg_header += 'width="' + svgwidth + uom + '" '
  4259. svg_header += 'height="' + svgheight + uom + '" '
  4260. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4261. svg_header += '>'
  4262. svg_header += '<g transform="scale(1,-1)">'
  4263. svg_footer = '</g> </svg>'
  4264. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  4265. self.progress.emit(90)
  4266. # Parse the xml through a xml parser just to add line feeds
  4267. # and to make it look more pretty for the output
  4268. doc = parse_xml_string(svg_elem)
  4269. with open(filename, 'w') as fp:
  4270. fp.write(doc.toprettyxml())
  4271. self.progress.emit(100)
  4272. self.file_saved.emit("SVG", filename)
  4273. self.inform.emit("[success] SVG file exported to " + filename)
  4274. if use_thread is True:
  4275. proc = self.proc_container.new("Generating Film ... Please wait.")
  4276. def job_thread_film(app_obj):
  4277. try:
  4278. make_black_film()
  4279. except Exception as e:
  4280. proc.done()
  4281. return
  4282. proc.done()
  4283. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4284. else:
  4285. make_black_film()
  4286. def export_excellon(self, obj_name, filename, altium_format=None, use_thread=True):
  4287. """
  4288. Exports a Geometry Object to an Excellon file.
  4289. :param filename: Path to the Excellon file to save to.
  4290. :return:
  4291. """
  4292. if filename is None:
  4293. filename = self.defaults["global_last_save_folder"]
  4294. self.log.debug("export_excellon()")
  4295. format_exc = ';FILE_FORMAT=2:4\n'
  4296. units = ''
  4297. try:
  4298. obj = self.collection.get_by_name(str(obj_name))
  4299. except:
  4300. # TODO: The return behavior has not been established... should raise exception?
  4301. return "Could not retrieve object: %s" % obj_name
  4302. # updated units
  4303. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4304. if units == 'IN' or units == 'INCH':
  4305. units = 'INCH'
  4306. elif units == 'MM' or units == 'METRIC':
  4307. units ='METRIC'
  4308. def make_excellon():
  4309. try:
  4310. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4311. header = 'M48\n'
  4312. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4313. (str(self.app.version), str(self.app.version_date))
  4314. header += ';Filename: %s' % str(obj_name) + '\n'
  4315. header += ';Created on : %s' % time_str + '\n'
  4316. if altium_format == None:
  4317. has_slots, excellon_code = obj.export_excellon()
  4318. header += units + '\n'
  4319. for tool in obj.tools:
  4320. if units == 'METRIC':
  4321. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.2f' % float(obj.tools[tool]['C']) + '\n'
  4322. else:
  4323. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  4324. else:
  4325. has_slots, excellon_code = obj.export_excellon_altium()
  4326. header += 'INCH,LZ\n'
  4327. header += format_exc
  4328. for tool in obj.tools:
  4329. if units == 'METRIC':
  4330. header += 'T' + str(tool) + 'F00S00' + 'C' + \
  4331. '%.4f' % (float(obj.tools[tool]['C']) / 25.4) + '\n'
  4332. else:
  4333. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  4334. header += '%\n'
  4335. footer = 'M30\n'
  4336. exported_excellon = header
  4337. exported_excellon += excellon_code
  4338. exported_excellon += footer
  4339. with open(filename, 'w') as fp:
  4340. fp.write(exported_excellon)
  4341. self.file_saved.emit("Excellon", filename)
  4342. self.inform.emit("[success] Excellon file exported to " + filename)
  4343. except:
  4344. return 'fail'
  4345. if use_thread is True:
  4346. with self.proc_container.new("Exporting Excellon") as proc:
  4347. def job_thread_exc(app_obj):
  4348. ret = make_excellon()
  4349. if ret == 'fail':
  4350. self.inform.emit('[error_notcl] Could not export Excellon file.')
  4351. return
  4352. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4353. else:
  4354. ret = make_excellon()
  4355. if ret == 'fail':
  4356. self.inform.emit('[error_notcl] Could not export Excellon file.')
  4357. return
  4358. def export_dxf(self, obj_name, filename, use_thread=True):
  4359. """
  4360. Exports a Geometry Object to an DXF file.
  4361. :param filename: Path to the DXF file to save to.
  4362. :return:
  4363. """
  4364. if filename is None:
  4365. filename = self.defaults["global_last_save_folder"]
  4366. self.log.debug("export_dxf()")
  4367. format_exc = ''
  4368. units = ''
  4369. try:
  4370. obj = self.collection.get_by_name(str(obj_name))
  4371. except:
  4372. # TODO: The return behavior has not been established... should raise exception?
  4373. return "Could not retrieve object: %s" % obj_name
  4374. # updated units
  4375. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4376. if units == 'IN' or units == 'INCH':
  4377. units = 'INCH'
  4378. elif units == 'MM' or units == 'METIRC':
  4379. units ='METRIC'
  4380. def make_dxf():
  4381. try:
  4382. dxf_code = obj.export_dxf()
  4383. dxf_code.saveas(filename)
  4384. self.file_saved.emit("DXF", filename)
  4385. self.inform.emit("[success] DXF file exported to " + filename)
  4386. except:
  4387. return 'fail'
  4388. if use_thread is True:
  4389. with self.proc_container.new("Exporting DXF") as proc:
  4390. def job_thread_exc(app_obj):
  4391. ret = make_dxf()
  4392. if ret == 'fail':
  4393. self.inform.emit('[[warning_notcl]] Could not export DXF file.')
  4394. return
  4395. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4396. else:
  4397. ret = make_dxf()
  4398. if ret == 'fail':
  4399. self.inform.emit('[[warning_notcl]] Could not export DXF file.')
  4400. return
  4401. def import_svg(self, filename, geo_type='geometry', outname=None):
  4402. """
  4403. Adds a new Geometry Object to the projects and populates
  4404. it with shapes extracted from the SVG file.
  4405. :param filename: Path to the SVG file.
  4406. :param outname:
  4407. :return:
  4408. """
  4409. obj_type = ""
  4410. if geo_type is None or geo_type == "geometry":
  4411. obj_type = "geometry"
  4412. elif geo_type == "gerber":
  4413. obj_type = geo_type
  4414. else:
  4415. self.inform.emit("[error_notcl] Not supported type was choosed as parameter. "
  4416. "Only Geometry and Gerber are supported")
  4417. return
  4418. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4419. def obj_init(geo_obj, app_obj):
  4420. geo_obj.import_svg(filename, obj_type, units=units)
  4421. geo_obj.multigeo = False
  4422. with self.proc_container.new("Importing SVG") as proc:
  4423. # Object name
  4424. name = outname or filename.split('/')[-1].split('\\')[-1]
  4425. self.new_object(obj_type, name, obj_init, autoselected=False)
  4426. self.progress.emit(20)
  4427. # Register recent file
  4428. self.file_opened.emit("svg", filename)
  4429. # GUI feedback
  4430. self.inform.emit("[success] Opened: " + filename)
  4431. self.progress.emit(100)
  4432. def import_dxf(self, filename, geo_type='geometry', outname=None):
  4433. """
  4434. Adds a new Geometry Object to the projects and populates
  4435. it with shapes extracted from the DXF file.
  4436. :param filename: Path to the DXF file.
  4437. :param outname:
  4438. :type putname: str
  4439. :return:
  4440. """
  4441. obj_type = ""
  4442. if geo_type is None or geo_type == "geometry":
  4443. obj_type = "geometry"
  4444. elif geo_type == "gerber":
  4445. obj_type = geo_type
  4446. else:
  4447. self.inform.emit("[error_notcl] Not supported type was choosed as parameter. "
  4448. "Only Geometry and Gerber are supported")
  4449. return
  4450. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4451. def obj_init(geo_obj, app_obj):
  4452. geo_obj.import_dxf(filename, obj_type, units=units)
  4453. geo_obj.multigeo = False
  4454. with self.proc_container.new("Importing DXF") as proc:
  4455. # Object name
  4456. name = outname or filename.split('/')[-1].split('\\')[-1]
  4457. self.new_object(obj_type, name, obj_init, autoselected=False)
  4458. self.progress.emit(20)
  4459. # Register recent file
  4460. self.file_opened.emit("dxf", filename)
  4461. # GUI feedback
  4462. self.inform.emit("[success] Opened: " + filename)
  4463. self.progress.emit(100)
  4464. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  4465. """
  4466. Adds a new Geometry Object to the projects and populates
  4467. it with shapes extracted from the SVG file.
  4468. :param filename: Path to the SVG file.
  4469. :param outname:
  4470. :return:
  4471. """
  4472. obj_type = ""
  4473. if type is None or type == "geometry":
  4474. obj_type = "geometry"
  4475. elif type == "gerber":
  4476. obj_type = type
  4477. else:
  4478. self.inform.emit("[error_notcl] Not supported type was picked as parameter. "
  4479. "Only Geometry and Gerber are supported")
  4480. return
  4481. def obj_init(geo_obj, app_obj):
  4482. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  4483. geo_obj.multigeo = False
  4484. with self.proc_container.new("Importing Image") as proc:
  4485. # Object name
  4486. name = outname or filename.split('/')[-1].split('\\')[-1]
  4487. units = self.general_options_form.general_app_group.units_radio.get_value()
  4488. self.new_object(obj_type, name, obj_init)
  4489. self.progress.emit(20)
  4490. # Register recent file
  4491. self.file_opened.emit("image", filename)
  4492. # GUI feedback
  4493. self.inform.emit("[success] Opened: " + filename)
  4494. self.progress.emit(100)
  4495. def open_gerber(self, filename, follow=False, outname=None):
  4496. """
  4497. Opens a Gerber file, parses it and creates a new object for
  4498. it in the program. Thread-safe.
  4499. :param outname: Name of the resulting object. None causes the
  4500. name to be that of the file.
  4501. :param filename: Gerber file filename
  4502. :type filename: str
  4503. :param follow: If true, the parser will not create polygons, just lines
  4504. following the gerber path.
  4505. :type follow: bool
  4506. :return: None
  4507. """
  4508. # How the object should be initialized
  4509. def obj_init(gerber_obj, app_obj):
  4510. assert isinstance(gerber_obj, FlatCAMGerber), \
  4511. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  4512. # Opening the file happens here
  4513. self.progress.emit(30)
  4514. try:
  4515. gerber_obj.parse_file(filename, follow=follow)
  4516. except IOError:
  4517. app_obj.inform.emit("[error_notcl] Failed to open file: " + filename)
  4518. app_obj.progress.emit(0)
  4519. self.inform.emit('[error_notcl] Failed to open file: ' + filename)
  4520. return "fail"
  4521. except ParseError as err:
  4522. app_obj.inform.emit("[error_notcl] Failed to parse file: " + filename + ". " + str(err))
  4523. app_obj.progress.emit(0)
  4524. self.log.error(str(err))
  4525. return "fail"
  4526. except:
  4527. msg = "[error] An internal error has ocurred. See shell.\n"
  4528. msg += traceback.format_exc()
  4529. app_obj.inform.emit(msg)
  4530. return "fail"
  4531. if gerber_obj.is_empty():
  4532. # app_obj.inform.emit("[error] No geometry found in file: " + filename)
  4533. # self.collection.set_active(gerber_obj.options["name"])
  4534. # self.collection.delete_active()
  4535. self.inform.emit("[error_notcl] Object is not Gerber file or empty. Aborting object creation.")
  4536. return "fail"
  4537. # Further parsing
  4538. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  4539. if follow is False:
  4540. App.log.debug("open_gerber()")
  4541. else:
  4542. App.log.debug("open_gerber() with 'follow' attribute")
  4543. with self.proc_container.new("Opening Gerber") as proc:
  4544. self.progress.emit(10)
  4545. # Object name
  4546. name = outname or filename.split('/')[-1].split('\\')[-1]
  4547. ### Object creation ###
  4548. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  4549. if ret == 'fail':
  4550. self.inform.emit('[error_notcl] Open Gerber failed. Probable not a Gerber file.')
  4551. return
  4552. # Register recent file
  4553. self.file_opened.emit("gerber", filename)
  4554. self.progress.emit(100)
  4555. # GUI feedback
  4556. self.inform.emit("[success] Opened: " + filename)
  4557. def open_excellon(self, filename, outname=None):
  4558. """
  4559. Opens an Excellon file, parses it and creates a new object for
  4560. it in the program. Thread-safe.
  4561. :param outname: Name of the resulting object. None causes the
  4562. name to be that of the file.
  4563. :param filename: Excellon file filename
  4564. :type filename: str
  4565. :return: None
  4566. """
  4567. App.log.debug("open_excellon()")
  4568. #self.progress.emit(10)
  4569. # How the object should be initialized
  4570. def obj_init(excellon_obj, app_obj):
  4571. # self.progress.emit(20)
  4572. try:
  4573. ret = excellon_obj.parse_file(filename)
  4574. if ret == "fail":
  4575. log.debug("Excellon parsing failed.")
  4576. self.inform.emit("[error_notcl] This is not Excellon file.")
  4577. return "fail"
  4578. except IOError:
  4579. app_obj.inform.emit("[error_notcl] Cannot open file: " + filename)
  4580. log.debug("Could not open Excellon object.")
  4581. self.progress.emit(0) # TODO: self and app_bjj mixed
  4582. return "fail"
  4583. except:
  4584. msg = "[error_notcl] An internal error has occurred. See shell.\n"
  4585. msg += traceback.format_exc()
  4586. app_obj.inform.emit(msg)
  4587. return "fail"
  4588. ret = excellon_obj.create_geometry()
  4589. if ret == 'fail':
  4590. log.debug("Could not create geometry for Excellon object.")
  4591. return "fail"
  4592. if excellon_obj.is_empty():
  4593. app_obj.inform.emit("[error_notcl] No geometry found in file: " + filename)
  4594. return "fail"
  4595. with self.proc_container.new("Opening Excellon."):
  4596. # Object name
  4597. name = outname or filename.split('/')[-1].split('\\')[-1]
  4598. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  4599. if ret == 'fail':
  4600. self.inform.emit('[error_notcl] Open Excellon file failed. Probable not an Excellon file.')
  4601. return
  4602. # Register recent file
  4603. self.file_opened.emit("excellon", filename)
  4604. # GUI feedback
  4605. self.inform.emit("[success] Opened: " + filename)
  4606. # self.progress.emit(100)
  4607. def open_gcode(self, filename, outname=None):
  4608. """
  4609. Opens a G-gcode file, parses it and creates a new object for
  4610. it in the program. Thread-safe.
  4611. :param outname: Name of the resulting object. None causes the
  4612. name to be that of the file.
  4613. :param filename: G-code file filename
  4614. :type filename: str
  4615. :return: None
  4616. """
  4617. App.log.debug("open_gcode()")
  4618. # How the object should be initialized
  4619. def obj_init(job_obj, app_obj_):
  4620. """
  4621. :type app_obj_: App
  4622. """
  4623. assert isinstance(app_obj_, App), \
  4624. "Initializer expected App, got %s" % type(app_obj_)
  4625. self.progress.emit(10)
  4626. try:
  4627. f = open(filename)
  4628. gcode = f.read()
  4629. f.close()
  4630. except IOError:
  4631. app_obj_.inform.emit("[error_notcl] Failed to open " + filename)
  4632. self.progress.emit(0)
  4633. return "fail"
  4634. job_obj.gcode = gcode
  4635. self.progress.emit(20)
  4636. ret = job_obj.gcode_parse()
  4637. if ret == "fail":
  4638. self.inform.emit("[error_notcl] This is not GCODE")
  4639. return "fail"
  4640. self.progress.emit(60)
  4641. job_obj.create_geometry()
  4642. with self.proc_container.new("Opening G-Code."):
  4643. # Object name
  4644. name = outname or filename.split('/')[-1].split('\\')[-1]
  4645. # New object creation and file processing
  4646. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  4647. if ret == 'fail':
  4648. self.inform.emit("[error_notcl] Failed to create CNCJob Object. Probable not a GCode file.\n "
  4649. "Attempting to create a FlatCAM CNCJob Object from "
  4650. "G-Code file failed during processing")
  4651. return "fail"
  4652. # Register recent file
  4653. self.file_opened.emit("cncjob", filename)
  4654. # GUI feedback
  4655. self.inform.emit("[success] Opened: " + filename)
  4656. self.progress.emit(100)
  4657. def open_project(self, filename, run_from_arg=None):
  4658. """
  4659. Loads a project from the specified file.
  4660. 1) Loads and parses file
  4661. 2) Registers the file as recently opened.
  4662. 3) Calls on_file_new()
  4663. 4) Updates options
  4664. 5) Calls new_object() with the object's from_dict() as init method.
  4665. 6) Calls plot_all()
  4666. :param filename: Name of the file from which to load.
  4667. :type filename: str
  4668. :return: None
  4669. """
  4670. App.log.debug("Opening project: " + filename)
  4671. # Open and parse
  4672. try:
  4673. f = open(filename, 'r')
  4674. except IOError:
  4675. App.log.error("Failed to open project file: %s" % filename)
  4676. self.inform.emit("[error_notcl] Failed to open project file: %s" % filename)
  4677. return
  4678. try:
  4679. d = json.load(f, object_hook=dict2obj)
  4680. except:
  4681. App.log.error("Failed to parse project file: %s" % filename)
  4682. self.inform.emit("[error_notcl] Failed to parse project file: %s" % filename)
  4683. f.close()
  4684. return
  4685. self.file_opened.emit("project", filename)
  4686. # Clear the current project
  4687. ## NOT THREAD SAFE ##
  4688. if run_from_arg is True:
  4689. pass
  4690. else:
  4691. self.on_file_new()
  4692. #Project options
  4693. self.options.update(d['options'])
  4694. self.project_filename = filename
  4695. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4696. self.set_screen_units(self.options["units"])
  4697. # Re create objects
  4698. App.log.debug("Re-creating objects...")
  4699. for obj in d['objs']:
  4700. def obj_init(obj_inst, app_inst):
  4701. obj_inst.from_dict(obj)
  4702. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  4703. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  4704. # self.plot_all()
  4705. self.inform.emit("[success] Project loaded from: " + filename)
  4706. App.log.debug("Project loaded")
  4707. def propagate_defaults(self, silent=False):
  4708. """
  4709. This method is used to set default values in classes. It's
  4710. an alternative to project options but allows the use
  4711. of values invisible to the user.
  4712. :return: None
  4713. """
  4714. if silent is False:
  4715. self.log.debug("propagate_defaults()")
  4716. # Which objects to update the given parameters.
  4717. routes = {
  4718. "global_zdownrate": CNCjob,
  4719. "excellon_zeros": Excellon,
  4720. "excellon_format_upper_in": Excellon,
  4721. "excellon_format_lower_in": Excellon,
  4722. "excellon_format_upper_mm": Excellon,
  4723. "excellon_format_lower_mm": Excellon,
  4724. "excellon_units": Excellon,
  4725. "gerber_use_buffer_for_union": Gerber,
  4726. "geometry_multidepth": Geometry
  4727. }
  4728. for param in routes:
  4729. if param in routes[param].defaults:
  4730. try:
  4731. routes[param].defaults[param] = self.defaults[param]
  4732. if silent is False:
  4733. self.log.debug(" " + param + " OK")
  4734. except KeyError:
  4735. if silent is False:
  4736. self.log.debug(" ERROR: " + param + " not in defaults.")
  4737. else:
  4738. # Try extracting the name:
  4739. # classname_param here is param in the object
  4740. if param.find(routes[param].__name__.lower() + "_") == 0:
  4741. p = param[len(routes[param].__name__) + 1:]
  4742. if p in routes[param].defaults:
  4743. routes[param].defaults[p] = self.defaults[param]
  4744. if silent is False:
  4745. self.log.debug(" " + param + " OK!")
  4746. def restore_main_win_geom(self):
  4747. try:
  4748. self.ui.setGeometry(self.defaults["global_def_win_x"],
  4749. self.defaults["global_def_win_y"],
  4750. self.defaults["global_def_win_w"],
  4751. self.defaults["global_def_win_h"])
  4752. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  4753. except KeyError:
  4754. pass
  4755. def plot_all(self):
  4756. """
  4757. Re-generates all plots from all objects.
  4758. :return: None
  4759. """
  4760. self.log.debug("Plot_all()")
  4761. for obj in self.collection.get_list():
  4762. def worker_task(obj):
  4763. with self.proc_container.new("Plotting"):
  4764. obj.plot()
  4765. self.object_plotted.emit(obj)
  4766. # Send to worker
  4767. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  4768. # self.progress.emit(10)
  4769. #
  4770. # def worker_task(app_obj):
  4771. # print "worker task"
  4772. # percentage = 0.1
  4773. # try:
  4774. # delta = 0.9 / len(self.collection.get_list())
  4775. # except ZeroDivisionError:
  4776. # self.progress.emit(0)
  4777. # return
  4778. # for obj in self.collection.get_list():
  4779. # with self.proc_container.new("Plotting"):
  4780. # obj.plot()
  4781. # app_obj.object_plotted.emit(obj)
  4782. #
  4783. # percentage += delta
  4784. # self.progress.emit(int(percentage*100))
  4785. #
  4786. # self.progress.emit(0)
  4787. # self.plots_updated.emit()
  4788. #
  4789. # # Send to worker
  4790. # #self.worker.add_task(worker_task, [self])
  4791. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  4792. def register_folder(self, filename):
  4793. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  4794. def register_save_folder(self, filename):
  4795. self.defaults['global_last_save_folder'] = os.path.split(str(filename))[0]
  4796. def set_progress_bar(self, percentage, text=""):
  4797. self.ui.progress_bar.setValue(int(percentage))
  4798. def setup_shell(self):
  4799. """
  4800. Creates shell functions. Runs once at startup.
  4801. :return: None
  4802. """
  4803. self.log.debug("setup_shell()")
  4804. def shelp(p=None):
  4805. if not p:
  4806. return "Available commands:\n" + \
  4807. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  4808. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  4809. if p not in commands:
  4810. return "Unknown command: %s" % p
  4811. return commands[p]["help"]
  4812. # --- Migrated to new architecture ---
  4813. # def options(name):
  4814. # ops = self.collection.get_by_name(str(name)).options
  4815. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  4816. def h(*args):
  4817. """
  4818. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  4819. and standalone parameters into list.
  4820. """
  4821. kwa = {}
  4822. a = []
  4823. n = len(args)
  4824. name = None
  4825. for i in range(n):
  4826. match = re.search(r'^-([a-zA-Z].*)', args[i])
  4827. if match:
  4828. assert name is None
  4829. name = match.group(1)
  4830. continue
  4831. if name is None:
  4832. a.append(args[i])
  4833. else:
  4834. kwa[name] = args[i]
  4835. name = None
  4836. return a, kwa
  4837. @contextmanager
  4838. def wait_signal(signal, timeout=10000):
  4839. """
  4840. Block loop until signal emitted, timeout (ms) elapses
  4841. or unhandled exception happens in a thread.
  4842. :param signal: Signal to wait for.
  4843. """
  4844. loop = QtCore.QEventLoop()
  4845. # Normal termination
  4846. signal.connect(loop.quit)
  4847. # Termination by exception in thread
  4848. self.thread_exception.connect(loop.quit)
  4849. status = {'timed_out': False}
  4850. def report_quit():
  4851. status['timed_out'] = True
  4852. loop.quit()
  4853. yield
  4854. # Temporarily change how exceptions are managed.
  4855. oeh = sys.excepthook
  4856. ex = []
  4857. def except_hook(type_, value, traceback_):
  4858. ex.append(value)
  4859. oeh(type_, value, traceback_)
  4860. sys.excepthook = except_hook
  4861. # Terminate on timeout
  4862. if timeout is not None:
  4863. QtCore.QTimer.singleShot(timeout, report_quit)
  4864. #### Block ####
  4865. loop.exec_()
  4866. # Restore exception management
  4867. sys.excepthook = oeh
  4868. if ex:
  4869. self.raiseTclError(str(ex[0]))
  4870. if status['timed_out']:
  4871. raise Exception('Timed out!')
  4872. def make_docs():
  4873. output = ''
  4874. import collections
  4875. od = collections.OrderedDict(sorted(commands.items()))
  4876. for cmd_, val in od.items():
  4877. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  4878. t = val['help']
  4879. usage_i = t.find('>')
  4880. if usage_i < 0:
  4881. expl = t
  4882. output += expl + '\n\n'
  4883. continue
  4884. expl = t[:usage_i - 1]
  4885. output += expl + '\n\n'
  4886. end_usage_i = t[usage_i:].find('\n')
  4887. if end_usage_i < 0:
  4888. end_usage_i = len(t[usage_i:])
  4889. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  4890. else:
  4891. extras = t[usage_i+end_usage_i+1:]
  4892. parts = [s.strip() for s in extras.split('\n')]
  4893. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  4894. for p in parts:
  4895. output += ' ' + p + '\n\n'
  4896. return output
  4897. '''
  4898. Howto implement TCL shell commands:
  4899. All parameters passed to command should be possible to set as None and test it afterwards.
  4900. This is because we need to see error caused in tcl,
  4901. if None value as default parameter is not allowed TCL will return empty error.
  4902. Use:
  4903. def mycommand(name=None,...):
  4904. Test it like this:
  4905. if name is None:
  4906. self.raise_tcl_error('Argument name is missing.')
  4907. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  4908. otherwise we will miss it and processing will silently continue.
  4909. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  4910. which is catched in exec_command and displayed in TCL shell console with red background.
  4911. Error in console is displayed with TCL trace.
  4912. This behavior works only within main thread,
  4913. errors with promissed tasks can be catched and detected only with log.
  4914. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  4915. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  4916. '''
  4917. commands = {
  4918. 'help': {
  4919. 'fcn': shelp,
  4920. 'help': "Shows list of commands."
  4921. },
  4922. }
  4923. # Import/overwrite tcl commands as objects of TclCommand descendants
  4924. # This modifies the variable 'commands'.
  4925. tclCommands.register_all_commands(self, commands)
  4926. # Add commands to the tcl interpreter
  4927. for cmd in commands:
  4928. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  4929. # Make the tcl puts function return instead of print to stdout
  4930. self.tcl.eval('''
  4931. rename puts original_puts
  4932. proc puts {args} {
  4933. if {[llength $args] == 1} {
  4934. return "[lindex $args 0]"
  4935. } else {
  4936. eval original_puts $args
  4937. }
  4938. }
  4939. ''')
  4940. def setup_recent_items(self):
  4941. # TODO: Move this to constructor
  4942. icons = {
  4943. "gerber": "share/flatcam_icon16.png",
  4944. "excellon": "share/drill16.png",
  4945. "cncjob": "share/cnc16.png",
  4946. "project": "share/project16.png",
  4947. "svg": "share/geometry16.png",
  4948. "dxf": "share/dxf16.png",
  4949. "image": "share/image16.png"
  4950. }
  4951. openers = {
  4952. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  4953. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  4954. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  4955. 'project': self.open_project,
  4956. 'svg': self.import_svg,
  4957. 'dxf': self.import_dxf,
  4958. 'image': self.import_image
  4959. }
  4960. # Open file
  4961. try:
  4962. f = open(self.data_path + '/recent.json')
  4963. except IOError:
  4964. App.log.error("Failed to load recent item list.")
  4965. self.inform.emit("[error_notcl] Failed to load recent item list.")
  4966. return
  4967. try:
  4968. self.recent = json.load(f)
  4969. except json.scanner.JSONDecodeError:
  4970. App.log.error("Failed to parse recent item list.")
  4971. self.inform.emit("[error_notcl] Failed to parse recent item list.")
  4972. f.close()
  4973. return
  4974. f.close()
  4975. # Closure needed to create callbacks in a loop.
  4976. # Otherwise late binding occurs.
  4977. def make_callback(func, fname):
  4978. def opener():
  4979. func(fname)
  4980. return opener
  4981. def reset_recent():
  4982. # Reset menu
  4983. self.ui.recent.clear()
  4984. self.recent = []
  4985. try:
  4986. f = open(self.data_path + '/recent.json', 'w')
  4987. except IOError:
  4988. App.log.error("Failed to open recent items file for writing.")
  4989. return
  4990. json.dump(self.recent, f)
  4991. # Reset menu
  4992. self.ui.recent.clear()
  4993. # Create menu items
  4994. for recent in self.recent:
  4995. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  4996. try:
  4997. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  4998. # Attach callback
  4999. o = make_callback(openers[recent["kind"]], recent['filename'])
  5000. action.triggered.connect(o)
  5001. self.ui.recent.addAction(action)
  5002. except KeyError:
  5003. App.log.error("Unsupported file type: %s" % recent["kind"])
  5004. # Last action in Recent Files menu is one that Clear the content
  5005. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  5006. clear_action.triggered.connect(reset_recent)
  5007. self.ui.recent.addSeparator()
  5008. self.ui.recent.addAction(clear_action)
  5009. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  5010. # self.ui.menufilerecent.set_submenu(recent_menu)
  5011. # recent_menu.show_all()
  5012. # self.ui.recent.show()
  5013. self.log.debug("Recent items list has been populated.")
  5014. def setup_component_editor(self):
  5015. label = QtWidgets.QLabel("Choose an item from Project")
  5016. label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  5017. self.ui.selected_scroll_area.setWidget(label)
  5018. def setup_obj_classes(self):
  5019. """
  5020. Sets up application specifics on the FlatCAMObj class.
  5021. :return: None
  5022. """
  5023. FlatCAMObj.app = self
  5024. ObjectCollection.app = self
  5025. FCProcess.app = self
  5026. FCProcessContainer.app = self
  5027. def version_check(self):
  5028. """
  5029. Checks for the latest version of the program. Alerts the
  5030. user if theirs is outdated. This method is meant to be run
  5031. in a separate thread.
  5032. :return: None
  5033. """
  5034. self.log.debug("version_check()")
  5035. if self.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  5036. full_url = App.version_url + \
  5037. "?s=" + str(self.defaults['global_serial']) + \
  5038. "&v=" + str(self.version) + \
  5039. "&os=" + str(self.os) + \
  5040. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  5041. else:
  5042. # no_stats dict; just so it won't break things on website
  5043. no_ststs_dict = {}
  5044. no_ststs_dict["global_ststs"] = {}
  5045. full_url = App.version_url + \
  5046. "?s=" + str(self.defaults['global_serial']) + \
  5047. "&v=" + str(self.version) + \
  5048. "&os=" + str(self.os) + \
  5049. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  5050. App.log.debug("Checking for updates @ %s" % full_url)
  5051. ### Get the data
  5052. try:
  5053. f = urllib.request.urlopen(full_url)
  5054. except:
  5055. # App.log.warning("Failed checking for latest version. Could not connect.")
  5056. self.log.warning("Failed checking for latest version. Could not connect.")
  5057. self.inform.emit("[warning_notcl] Failed checking for latest version. Could not connect.")
  5058. return
  5059. try:
  5060. data = json.load(f)
  5061. except Exception as e:
  5062. App.log.error("Could not parse information about latest version.")
  5063. self.inform.emit("[error_notcl] Could not parse information about latest version.")
  5064. App.log.debug("json.load(): %s" % str(e))
  5065. f.close()
  5066. return
  5067. f.close()
  5068. ### Latest version?
  5069. if self.version >= data["version"]:
  5070. App.log.debug("FlatCAM is up to date!")
  5071. self.inform.emit("[success] FlatCAM is up to date!")
  5072. return
  5073. App.log.debug("Newer version available.")
  5074. self.message.emit(
  5075. "Newer Version Available",
  5076. str("There is a newer version of FlatCAM " +
  5077. "available for download:<br><br>" +
  5078. "<B>" + data["name"] + "</b><br>" +
  5079. data["message"].replace("\n", "<br>")),
  5080. "info"
  5081. )
  5082. def on_zoom_fit(self, event):
  5083. """
  5084. Callback for zoom-out request. This can be either from the corresponding
  5085. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  5086. with axes limits from the geometry bounds of all objects.
  5087. :param event: Ignored.
  5088. :return: None
  5089. """
  5090. self.plotcanvas.fit_view()
  5091. def disable_all_plots(self):
  5092. self.disable_plots(self.collection.get_list())
  5093. self.inform.emit("[success]All plots disabled.")
  5094. def disable_other_plots(self):
  5095. self.disable_plots(self.collection.get_non_selected())
  5096. self.inform.emit("[success]All non selected plots disabled.")
  5097. def enable_all_plots(self):
  5098. self.enable_plots(self.collection.get_list())
  5099. self.inform.emit("[success]All plots enabled.")
  5100. # TODO: FIX THIS
  5101. '''
  5102. By default this is not threaded
  5103. If threaded the app give warnings like this:
  5104. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5105. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5106. '''
  5107. def enable_plots(self, objects, threaded=False):
  5108. if threaded is True:
  5109. def worker_task(app_obj):
  5110. percentage = 0.1
  5111. try:
  5112. delta = 0.9 / len(objects)
  5113. except ZeroDivisionError:
  5114. self.progress.emit(0)
  5115. return
  5116. for obj in objects:
  5117. obj.options['plot'] = True
  5118. percentage += delta
  5119. self.progress.emit(int(percentage*100))
  5120. self.progress.emit(0)
  5121. self.plots_updated.emit()
  5122. self.collection.update_view()
  5123. # Send to worker
  5124. # self.worker.add_task(worker_task, [self])
  5125. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5126. else:
  5127. for obj in objects:
  5128. obj.options['plot'] = True
  5129. self.progress.emit(0)
  5130. self.plots_updated.emit()
  5131. self.collection.update_view()
  5132. # TODO: FIX THIS
  5133. '''
  5134. By default this is not threaded
  5135. If threaded the app give warnings like this:
  5136. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5137. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5138. '''
  5139. def disable_plots(self, objects, threaded=False):
  5140. # TODO: This method is very similar to replot_all. Try to merge.
  5141. """
  5142. Disables plots
  5143. :param objects: list
  5144. Objects to be disabled
  5145. :return:
  5146. """
  5147. if threaded is True:
  5148. self.progress.emit(10)
  5149. def worker_task(app_obj):
  5150. percentage = 0.1
  5151. try:
  5152. delta = 0.9 / len(objects)
  5153. except ZeroDivisionError:
  5154. self.progress.emit(0)
  5155. return
  5156. for obj in objects:
  5157. obj.options['plot'] = False
  5158. percentage += delta
  5159. self.progress.emit(int(percentage*100))
  5160. self.progress.emit(0)
  5161. self.plots_updated.emit()
  5162. self.collection.update_view()
  5163. # Send to worker
  5164. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5165. else:
  5166. for obj in objects:
  5167. obj.options['plot'] = False
  5168. self.plots_updated.emit()
  5169. self.collection.update_view()
  5170. def clear_plots(self):
  5171. objects = self.collection.get_list()
  5172. for obj in objects:
  5173. obj.clear(obj == objects[-1])
  5174. # Clear pool to free memory
  5175. self.clear_pool()
  5176. def generate_cnc_job(self, objects):
  5177. for obj in objects:
  5178. obj.generatecncjob()
  5179. def save_project(self, filename):
  5180. """
  5181. Saves the current project to the specified file.
  5182. :param filename: Name of the file in which to save.
  5183. :type filename: str
  5184. :return: None
  5185. """
  5186. self.log.debug("save_project()")
  5187. with self.proc_container.new("Saving FlatCAM Project") as proc:
  5188. ## Capture the latest changes
  5189. # Current object
  5190. try:
  5191. self.collection.get_active().read_form()
  5192. except:
  5193. self.log.debug("[warning] There was no active object")
  5194. pass
  5195. # Project options
  5196. self.options_read_form()
  5197. # Serialize the whole project
  5198. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  5199. "options": self.options,
  5200. "version": self.version}
  5201. # Open file
  5202. try:
  5203. f = open(filename, 'w')
  5204. except IOError:
  5205. App.log.error("[error] Failed to open file for saving: %s", filename)
  5206. return
  5207. # Write
  5208. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  5209. f.close()
  5210. # verification of the saved project
  5211. # Open and parse
  5212. try:
  5213. saved_f = open(filename, 'r')
  5214. except IOError:
  5215. self.inform.emit("[error_notcl] Failed to verify project file: %s. Retry to save it." % filename)
  5216. return
  5217. try:
  5218. saved_d = json.load(saved_f, object_hook=dict2obj)
  5219. except:
  5220. self.inform.emit("[error_notcl] Failed to parse saved project file: %s. Retry to save it." % filename)
  5221. f.close()
  5222. return
  5223. saved_f.close()
  5224. if 'version' in saved_d:
  5225. self.inform.emit("[success] Project saved to: %s" % filename)
  5226. else:
  5227. self.inform.emit("[error_notcl] Failed to save project file: %s. Retry to save it." % filename)
  5228. def on_options_app2project(self):
  5229. """
  5230. Callback for Options->Transfer Options->App=>Project. Copies options
  5231. from application defaults to project defaults.
  5232. :return: None
  5233. """
  5234. self.report_usage("on_options_app2project")
  5235. self.defaults_read_form()
  5236. self.options.update(self.defaults)
  5237. self.options_write_form()
  5238. def on_options_project2app(self):
  5239. """
  5240. Callback for Options->Transfer Options->Project=>App. Copies options
  5241. from project defaults to application defaults.
  5242. :return: None
  5243. """
  5244. self.report_usage("on_options_project2app")
  5245. self.options_read_form()
  5246. self.defaults.update(self.options)
  5247. self.defaults_write_form()
  5248. def on_options_project2object(self):
  5249. """
  5250. Callback for Options->Transfer Options->Project=>Object. Copies options
  5251. from project defaults to the currently selected object.
  5252. :return: None
  5253. """
  5254. self.report_usage("on_options_project2object")
  5255. self.options_read_form()
  5256. obj = self.collection.get_active()
  5257. if obj is None:
  5258. self.inform.emit("WARNING: No object selected.")
  5259. return
  5260. for option in self.options:
  5261. if option.find(obj.kind + "_") == 0:
  5262. oname = option[len(obj.kind) + 1:]
  5263. obj.options[oname] = self.options[option]
  5264. obj.to_form() # Update UI
  5265. def on_options_object2project(self):
  5266. """
  5267. Callback for Options->Transfer Options->Object=>Project. Copies options
  5268. from the currently selected object to project defaults.
  5269. :return: None
  5270. """
  5271. self.report_usage("on_options_object2project")
  5272. obj = self.collection.get_active()
  5273. if obj is None:
  5274. self.inform.emit("WARNING: No object selected.")
  5275. return
  5276. obj.read_form()
  5277. for option in obj.options:
  5278. if option in ['name']: # TODO: Handle this better...
  5279. continue
  5280. self.options[obj.kind + "_" + option] = obj.options[option]
  5281. self.options_write_form()
  5282. def on_options_object2app(self):
  5283. """
  5284. Callback for Options->Transfer Options->Object=>App. Copies options
  5285. from the currently selected object to application defaults.
  5286. :return: None
  5287. """
  5288. self.report_usage("on_options_object2app")
  5289. obj = self.collection.get_active()
  5290. if obj is None:
  5291. self.inform.emit("WARNING: No object selected.")
  5292. return
  5293. obj.read_form()
  5294. for option in obj.options:
  5295. if option in ['name']: # TODO: Handle this better...
  5296. continue
  5297. self.defaults[obj.kind + "_" + option] = obj.options[option]
  5298. self.defaults_write_form()
  5299. def on_options_app2object(self):
  5300. """
  5301. Callback for Options->Transfer Options->App=>Object. Copies options
  5302. from application defaults to the currently selected object.
  5303. :return: None
  5304. """
  5305. self.report_usage("on_options_app2object")
  5306. self.defaults_read_form()
  5307. obj = self.collection.get_active()
  5308. if obj is None:
  5309. self.inform.emit("WARNING: No object selected.")
  5310. return
  5311. for option in self.defaults:
  5312. if option.find(obj.kind + "_") == 0:
  5313. oname = option[len(obj.kind) + 1:]
  5314. obj.options[oname] = self.defaults[option]
  5315. obj.to_form() # Update UI
  5316. # end of file