FlatCAMApp.py 324 KB

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