FlatCAMApp.py 548 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092
  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
  9. import urllib.parse
  10. import urllib.error
  11. import webbrowser
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import lzma
  16. import threading
  17. import shutil
  18. import stat
  19. from stat import S_IREAD, S_IRGRP, S_IROTH
  20. import subprocess
  21. import ctypes
  22. import tkinter as tk
  23. from PyQt5 import QtPrintSupport
  24. from contextlib import contextmanager
  25. import gc
  26. from xml.dom.minidom import parseString as parse_xml_string
  27. from multiprocessing.connection import Listener, Client
  28. from multiprocessing import Pool, cpu_count
  29. import socket
  30. from array import array
  31. import vispy.scene as scene
  32. # #######################################
  33. # # Imports part of FlatCAM ##
  34. # #######################################
  35. from ObjectCollection import *
  36. from FlatCAMObj import *
  37. from camlib import to_dict, dict2obj, ET, ParseError
  38. from flatcamGUI.PlotCanvas import *
  39. from flatcamGUI.PlotCanvasLegacy import *
  40. from flatcamGUI.FlatCAMGUI import *
  41. from FlatCAMCommon import LoudDict, BookmarkManager, ToolsDB
  42. from FlatCAMPostProc import load_preprocessors
  43. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  44. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  45. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  46. from flatcamEditors.FlatCAMTextEditor import TextEditor
  47. from FlatCAMProcess import *
  48. from FlatCAMWorkerStack import WorkerStack
  49. # from flatcamGUI.VisPyVisuals import Color
  50. from vispy.gloo.util import _screenshot
  51. from vispy.io import write_png
  52. from flatcamTools import *
  53. import tclCommands
  54. import gettext
  55. import FlatCAMTranslation as fcTranslate
  56. import builtins
  57. if sys.platform == 'win32':
  58. import winreg
  59. fcTranslate.apply_language('strings')
  60. if '_' not in builtins.__dict__:
  61. _ = gettext.gettext
  62. class App(QtCore.QObject):
  63. # ########################################
  64. # # App ###
  65. # ########################################
  66. """
  67. The main application class. The constructor starts the GUI.
  68. """
  69. # Get Cmd Line Options
  70. cmd_line_shellfile = ''
  71. cmd_line_shellvar = ''
  72. cmd_line_headless = None
  73. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  74. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  75. "FlatCam.py --headless=1"
  76. try:
  77. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  78. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  79. "shellvar=",
  80. "headless=",
  81. "multiprocessing-fork="])
  82. except getopt.GetoptError:
  83. print(cmd_line_help)
  84. sys.exit(2)
  85. for opt, arg in cmd_line_options:
  86. if opt == '-h':
  87. print(cmd_line_help)
  88. sys.exit()
  89. elif opt == '--shellfile':
  90. cmd_line_shellfile = arg
  91. elif opt == '--shellvar':
  92. cmd_line_shellvar = arg
  93. elif opt == '--headless':
  94. try:
  95. cmd_line_headless = eval(arg)
  96. except NameError:
  97. pass
  98. # ## Logging ###
  99. log = logging.getLogger('base')
  100. log.setLevel(logging.DEBUG)
  101. # log.setLevel(logging.WARNING)
  102. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  103. handler = logging.StreamHandler()
  104. handler.setFormatter(formatter)
  105. log.addHandler(handler)
  106. # ##########################################################################
  107. # ################## Version and VERSION DATE ##############################
  108. # ##########################################################################
  109. version = 8.99
  110. version_date = "2019/12/12"
  111. beta = True
  112. engine = '3D'
  113. # current date now
  114. date = str(datetime.today()).rpartition('.')[0]
  115. date = ''.join(c for c in date if c not in ':-')
  116. date = date.replace(' ', '_')
  117. # URL for update checks and statistics
  118. version_url = "http://flatcam.org/version"
  119. # App URL
  120. app_url = "http://flatcam.org"
  121. # Manual URL
  122. manual_url = "http://flatcam.org/manual/index.html"
  123. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  124. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  125. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  126. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  127. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  128. # this variable will hold the project status
  129. # if True it will mean that the project was modified and not saved
  130. should_we_save = False
  131. # flag is True if saving action has been triggered
  132. save_in_progress = False
  133. # ###########################################################################
  134. # ############################# Signals ################################
  135. # ###########################################################################
  136. # Inform the user
  137. # Handled by:
  138. # * App.info() --> Print on the status bar
  139. inform = QtCore.pyqtSignal(str)
  140. app_quit = QtCore.pyqtSignal()
  141. # General purpose background task
  142. worker_task = QtCore.pyqtSignal(dict)
  143. # File opened
  144. # Handled by:
  145. # * register_folder()
  146. # * register_recent()
  147. # Note: Setting the parameters to unicode does not seem
  148. # to have an effect. Then are received as Qstring
  149. # anyway.
  150. # File type and filename
  151. file_opened = QtCore.pyqtSignal(str, str)
  152. # File type and filename
  153. file_saved = QtCore.pyqtSignal(str, str)
  154. # Percentage of progress
  155. progress = QtCore.pyqtSignal(int)
  156. plots_updated = QtCore.pyqtSignal()
  157. # Emitted by new_object() and passes the new object as argument, plot flag.
  158. # on_object_created() adds the object to the collection, plots on appropriate flag
  159. # and emits new_object_available.
  160. object_created = QtCore.pyqtSignal(object, bool, bool)
  161. # Emitted when a object has been changed (like scaled, mirrored)
  162. object_changed = QtCore.pyqtSignal(object)
  163. # Emitted after object has been plotted.
  164. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  165. object_plotted = QtCore.pyqtSignal(object)
  166. # Emitted when a new object has been added or deleted from/to the collection
  167. object_status_changed = QtCore.pyqtSignal(object, str, str)
  168. message = QtCore.pyqtSignal(str, str, str)
  169. # Emmited when shell command is finished(one command only)
  170. shell_command_finished = QtCore.pyqtSignal(object)
  171. # Emitted when multiprocess pool has been recreated
  172. pool_recreated = QtCore.pyqtSignal(object)
  173. # Emitted when an unhandled exception happens
  174. # in the worker task.
  175. thread_exception = QtCore.pyqtSignal(object)
  176. # used to signal that there are arguments for the app
  177. args_at_startup = QtCore.pyqtSignal(list)
  178. # a reusable signal to replot a list of objects
  179. # should be disconnected after use so it can be reused
  180. replot_signal = pyqtSignal(list)
  181. def __init__(self, user_defaults=True):
  182. """
  183. Starts the application.
  184. :return: app
  185. :rtype: App
  186. """
  187. App.log.info("FlatCAM Starting...")
  188. self.main_thread = QtWidgets.QApplication.instance().thread()
  189. # ############################################################################
  190. # # ################# OS-specific ############################################
  191. # ############################################################################
  192. portable = False
  193. # Folder for user settings.
  194. if sys.platform == 'win32':
  195. # #########################################################################
  196. # Setup the listening thread for another instance launching with args #####
  197. # #########################################################################
  198. # make sure the thread is stored by using a self. otherwise it's garbage collected
  199. self.th = QtCore.QThread()
  200. self.th.start(priority=QtCore.QThread.LowestPriority)
  201. self.new_launch = ArgsThread()
  202. self.new_launch.open_signal[list].connect(self.on_startup_args)
  203. self.new_launch.moveToThread(self.th)
  204. self.new_launch.start.emit()
  205. from win32com.shell import shell, shellcon
  206. if platform.architecture()[0] == '32bit':
  207. App.log.debug("Win32!")
  208. else:
  209. App.log.debug("Win64!")
  210. # #########################################################################
  211. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  212. # #########################################################################
  213. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  214. try:
  215. with open(config_file, 'r'):
  216. pass
  217. except FileNotFoundError:
  218. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  219. try:
  220. with open(config_file, 'r') as f:
  221. try:
  222. for line in f:
  223. param = str(line).replace('\n', '').rpartition('=')
  224. if param[0] == 'portable':
  225. try:
  226. portable = eval(param[2])
  227. except NameError:
  228. portable = False
  229. if param[0] == 'headless':
  230. if param[2].lower() == 'true':
  231. self.cmd_line_headless = 1
  232. else:
  233. self.cmd_line_headless = None
  234. except Exception as e:
  235. log.debug('App.__init__() -->%s' % str(e))
  236. return
  237. except FileNotFoundError as e:
  238. log.debug(str(e))
  239. pass
  240. if portable is False:
  241. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  242. else:
  243. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  244. self.os = 'windows'
  245. else: # Linux/Unix/MacOS
  246. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  247. self.os = 'unix'
  248. # ##########################################################################
  249. # ################## Setup folders and files ###############################
  250. # ##########################################################################
  251. if not os.path.exists(self.data_path):
  252. os.makedirs(self.data_path)
  253. App.log.debug('Created data folder: ' + self.data_path)
  254. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  255. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  256. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  257. if not os.path.exists(self.preprocessorpaths):
  258. os.makedirs(self.preprocessorpaths)
  259. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  260. # create tools_db.FlatConfig file if there is none
  261. try:
  262. f = open(self.data_path + '/tools_db.FlatConfig')
  263. f.close()
  264. except IOError:
  265. App.log.debug('Creating empty tool_db.FlatConfig')
  266. f = open(self.data_path + '/tools_db.FlatConfig', 'w')
  267. json.dump({}, f)
  268. f.close()
  269. # create current_defaults.FlatConfig file if there is none
  270. try:
  271. f = open(self.data_path + '/current_defaults.FlatConfig')
  272. f.close()
  273. except IOError:
  274. App.log.debug('Creating empty current_defaults.FlatConfig')
  275. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  276. json.dump({}, f)
  277. f.close()
  278. # create factory_defaults.FlatConfig file if there is none
  279. try:
  280. f = open(self.data_path + '/factory_defaults.FlatConfig')
  281. f.close()
  282. except IOError:
  283. App.log.debug('Creating empty factory_defaults.FlatConfig')
  284. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  285. json.dump({}, f)
  286. f.close()
  287. # create a recent files json file if there is none
  288. try:
  289. f = open(self.data_path + '/recent.json')
  290. f.close()
  291. except IOError:
  292. App.log.debug('Creating empty recent.json')
  293. f = open(self.data_path + '/recent.json', 'w')
  294. json.dump([], f)
  295. f.close()
  296. # create a recent projects json file if there is none
  297. try:
  298. fp = open(self.data_path + '/recent_projects.json')
  299. fp.close()
  300. except IOError:
  301. App.log.debug('Creating empty recent_projects.json')
  302. fp = open(self.data_path + '/recent_projects.json', 'w')
  303. json.dump([], fp)
  304. fp.close()
  305. # Application directory. CHDIR to it. Otherwise, trying to load
  306. # GUI icons will fail as their path is relative.
  307. # This will fail under cx_freeze ...
  308. self.app_home = os.path.dirname(os.path.realpath(__file__))
  309. App.log.debug("Application path is " + self.app_home)
  310. App.log.debug("Started in " + os.getcwd())
  311. # cx_freeze workaround
  312. if os.path.isfile(self.app_home):
  313. self.app_home = os.path.dirname(self.app_home)
  314. os.chdir(self.app_home)
  315. # #################################################################################
  316. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  317. # #################################################################################
  318. self.defaults = LoudDict()
  319. self.defaults.update({
  320. # Global APP Preferences
  321. "decimals_inch": 4,
  322. "decimals_metric": 4,
  323. "version": self.version,
  324. "first_run": True,
  325. "units": "MM",
  326. "global_serial": 0,
  327. "global_stats": dict(),
  328. "global_tabs_detachable": True,
  329. "global_graphic_engine": '3D',
  330. "global_app_level": 'b',
  331. "global_portable": False,
  332. "global_language": 'English',
  333. "global_version_check": True,
  334. "global_send_stats": True,
  335. "global_pan_button": '2',
  336. "global_mselect_key": 'Control',
  337. "global_project_at_startup": False,
  338. "global_systray_icon": True,
  339. "global_project_autohide": True,
  340. "global_toggle_tooltips": True,
  341. "global_worker_number": 2,
  342. "global_tolerance": 0.005,
  343. "global_open_style": True,
  344. "global_delete_confirmation": True,
  345. "global_compression_level": 3,
  346. "global_save_compressed": True,
  347. "global_machinist_setting": False,
  348. # Global GUI Preferences
  349. "global_gridx": 1.0,
  350. "global_gridy": 1.0,
  351. "global_snap_max": 0.05,
  352. "global_workspace": False,
  353. "global_workspaceT": "A4",
  354. "global_workspace_orientation": 'p',
  355. "global_grid_context_menu": {
  356. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  357. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  358. },
  359. "global_plot_fill": '#BBF268BF',
  360. "global_plot_line": '#006E20BF',
  361. "global_sel_fill": '#a5a5ffbf',
  362. "global_sel_line": '#0000ffbf',
  363. "global_alt_sel_fill": '#BBF268BF',
  364. "global_alt_sel_line": '#006E20BF',
  365. "global_draw_color": '#FF0000',
  366. "global_sel_draw_color": '#0000FF',
  367. "global_proj_item_color": '#000000',
  368. "global_proj_item_dis_color": '#b7b7cb',
  369. "global_activity_icon": 'Ball green',
  370. "global_toolbar_view": 511,
  371. "global_background_timeout": 300000, # Default value is 5 minutes
  372. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  373. # (python trace only for unknown errors),
  374. # 1 = show trace(show trace always),
  375. # 2 = (For the future).
  376. # Persistence
  377. "global_last_folder": None,
  378. "global_last_save_folder": None,
  379. # Default window geometry
  380. "global_def_win_x": 100,
  381. "global_def_win_y": 100,
  382. "global_def_win_w": 1024,
  383. "global_def_win_h": 650,
  384. "global_def_notebook_width": 1,
  385. # Constants...
  386. "global_defaults_save_period_ms": 20000, # Time between default saves.
  387. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  388. "global_shell_at_startup": False, # Show the shell at startup.
  389. "global_recent_limit": 10, # Max. items in recent list.
  390. "global_bookmarks": dict(),
  391. "global_bookmarks_limit": 10,
  392. "fit_key": 'V',
  393. "zoom_out_key": '-',
  394. "zoom_in_key": '=',
  395. "grid_toggle_key": 'G',
  396. "global_zoom_ratio": 1.5,
  397. "global_point_clipboard_format": "(%.4f, %.4f)",
  398. "global_zdownrate": None,
  399. # General GUI Settings
  400. "global_theme": 'white',
  401. "global_hover": False,
  402. "global_selection_shape": True,
  403. "global_layout": "compact",
  404. "global_cursor_type": "small",
  405. "global_cursor_size": 20,
  406. # Gerber General
  407. "gerber_plot": True,
  408. "gerber_solid": True,
  409. "gerber_multicolored": False,
  410. "gerber_circle_steps": 64,
  411. "gerber_use_buffer_for_union": True,
  412. "gerber_def_units": 'IN',
  413. "gerber_def_zeros": 'L',
  414. "gerber_save_filters": "Gerber File (*.gbr);;Gerber File (*.bot);;Gerber File (*.bsm);;"
  415. "Gerber File (*.cmp);;Gerber File (*.crc);;Gerber File (*.crs);;"
  416. "Gerber File (*.gb0);;Gerber File (*.gb1);;Gerber File (*.gb2);;"
  417. "Gerber File (*.gb3);;Gerber File (*.gb4);;Gerber File (*.gb5);;"
  418. "Gerber File (*.gb6);;Gerber File (*.gb7);;Gerber File (*.gb8);;"
  419. "Gerber File (*.gb9);;Gerber File (*.gbd);;Gerber File (*.gbl);;"
  420. "Gerber File (*.gbo);;Gerber File (*.gbp);;Gerber File (*.gbs);;"
  421. "Gerber File (*.gdo);;Gerber File (*.ger);;Gerber File (*.gko);;"
  422. "Gerber File (*.gm1);;Gerber File (*.gm2);;Gerber File (*.gm3);;"
  423. "Gerber File (*.grb);;Gerber File (*.gtl);;Gerber File (*.gto);;"
  424. "Gerber File (*.gtp);;Gerber File (*.gts);;Gerber File (*.ly15);;"
  425. "Gerber File (*.ly2);;Gerber File (*.mil);;Gerber File (*.pho);;"
  426. "Gerber File (*.plc);;Gerber File (*.pls);;Gerber File (*.smb);;"
  427. "Gerber File (*.smt);;Gerber File (*.sol);;Gerber File (*.spb);;"
  428. "Gerber File (*.spt);;Gerber File (*.ssb);;Gerber File (*.sst);;"
  429. "Gerber File (*.stc);;Gerber File (*.sts);;Gerber File (*.top);;"
  430. "Gerber File (*.tsm);;Gerber File (*.art)"
  431. "All Files (*.*)",
  432. # Gerber Options
  433. "gerber_isotooldia": 0.1,
  434. "gerber_isopasses": 1,
  435. "gerber_isooverlap": 10,
  436. "gerber_milling_type": "cl",
  437. "gerber_combine_passes": False,
  438. "gerber_iso_scope": 'all',
  439. "gerber_noncoppermargin": 0.1,
  440. "gerber_noncopperrounded": False,
  441. "gerber_bboxmargin": 0.1,
  442. "gerber_bboxrounded": False,
  443. # Gerber Advanced Options
  444. "gerber_aperture_display": False,
  445. "gerber_aperture_scale_factor": 1.0,
  446. "gerber_aperture_buffer_factor": 0.0,
  447. "gerber_follow": False,
  448. "gerber_tool_type": 'circular',
  449. "gerber_vtipdia": 0.1,
  450. "gerber_vtipangle": 30,
  451. "gerber_vcutz": -0.05,
  452. "gerber_iso_type": "full",
  453. "gerber_buffering": "full",
  454. "gerber_simplification": False,
  455. "gerber_simp_tolerance": 0.0005,
  456. # Gerber Export
  457. "gerber_exp_units": 'IN',
  458. "gerber_exp_integer": 2,
  459. "gerber_exp_decimals": 4,
  460. "gerber_exp_zeros": 'L',
  461. # Gerber Editor
  462. "gerber_editor_sel_limit": 30,
  463. "gerber_editor_newcode": 10,
  464. "gerber_editor_newsize": 0.8,
  465. "gerber_editor_newtype": 'C',
  466. "gerber_editor_newdim": "0.5, 0.5",
  467. "gerber_editor_array_size": 5,
  468. "gerber_editor_lin_axis": 'X',
  469. "gerber_editor_lin_pitch": 0.1,
  470. "gerber_editor_lin_angle": 0.0,
  471. "gerber_editor_circ_dir": 'CW',
  472. "gerber_editor_circ_angle": 0.0,
  473. "gerber_editor_scale_f": 1.0,
  474. "gerber_editor_buff_f": 0.1,
  475. "gerber_editor_ma_low": 0.0,
  476. "gerber_editor_ma_high": 1.0,
  477. # Excellon General
  478. "excellon_plot": True,
  479. "excellon_solid": True,
  480. "excellon_format_upper_in": 2,
  481. "excellon_format_lower_in": 4,
  482. "excellon_format_upper_mm": 3,
  483. "excellon_format_lower_mm": 3,
  484. "excellon_zeros": "L",
  485. "excellon_units": "INCH",
  486. "excellon_update": True,
  487. "excellon_optimization_type": 'B',
  488. "excellon_search_time": 3,
  489. "excellon_save_filters": "Excellon File (*.txt);;Excellon File (*.drd);;Excellon File (*.drl);;"
  490. "Excellon File (*.exc);;Excellon File (*.ncd);;Excellon File (*.tap);;"
  491. "Excellon File (*.xln);;All Files (*.*)",
  492. # Excellon Options
  493. "excellon_drillz": -1.7,
  494. "excellon_travelz": 2,
  495. "excellon_endz": 0.5,
  496. "excellon_feedrate": 300,
  497. "excellon_spindlespeed": None,
  498. "excellon_dwell": False,
  499. "excellon_dwelltime": 1,
  500. "excellon_toolchange": False,
  501. "excellon_toolchangez": 15,
  502. "excellon_ppname_e": 'default',
  503. "excellon_tooldia": 0.8,
  504. "excellon_slot_tooldia": 1.8,
  505. "excellon_gcode_type": "drills",
  506. # Excellon Advanced Options
  507. "excellon_offset": 0.0,
  508. "excellon_toolchangexy": "0.0, 0.0",
  509. "excellon_startz": None,
  510. "excellon_feedrate_rapid": 1500,
  511. "excellon_z_pdepth": -0.02,
  512. "excellon_feedrate_probe": 75,
  513. "excellon_spindledir": 'CW',
  514. "excellon_f_plunge": False,
  515. "excellon_f_retract": False,
  516. # Excellon Export
  517. "excellon_exp_units": 'INCH',
  518. "excellon_exp_format": 'ndec',
  519. "excellon_exp_integer": 2,
  520. "excellon_exp_decimals": 4,
  521. "excellon_exp_zeros": 'LZ',
  522. "excellon_exp_slot_type": 'routing',
  523. # Excellon Editor
  524. "excellon_editor_sel_limit": 30,
  525. "excellon_editor_newdia": 1.0,
  526. "excellon_editor_array_size": 5,
  527. "excellon_editor_lin_dir": 'X',
  528. "excellon_editor_lin_pitch": 2.54,
  529. "excellon_editor_lin_angle": 0.0,
  530. "excellon_editor_circ_dir": 'CW',
  531. "excellon_editor_circ_angle": 12,
  532. # Excellon Slots
  533. "excellon_editor_slot_direction": 'X',
  534. "excellon_editor_slot_angle": 0.0,
  535. "excellon_editor_slot_length": 5.0,
  536. # Excellon Slot Array
  537. "excellon_editor_slot_array_size": 5,
  538. "excellon_editor_slot_lin_dir": 'X',
  539. "excellon_editor_slot_lin_pitch": 2.54,
  540. "excellon_editor_slot_lin_angle": 0.0,
  541. "excellon_editor_slot_circ_dir": 'CW',
  542. "excellon_editor_slot_circ_angle": 0.0,
  543. # Geometry General
  544. "geometry_plot": True,
  545. "geometry_circle_steps": 64,
  546. "geometry_cnctooldia": "2.4",
  547. # Geometry Options
  548. "geometry_cutz": -2.4,
  549. "geometry_vtipdia": 0.1,
  550. "geometry_vtipangle": 30,
  551. "geometry_multidepth": False,
  552. "geometry_depthperpass": 0.8,
  553. "geometry_travelz": 2,
  554. "geometry_toolchange": False,
  555. "geometry_toolchangez": 15.0,
  556. "geometry_endz": 15.0,
  557. "geometry_feedrate": 120,
  558. "geometry_feedrate_z": 60,
  559. "geometry_spindlespeed": None,
  560. "geometry_dwell": False,
  561. "geometry_dwelltime": 1,
  562. "geometry_ppname_g": 'default',
  563. # Geometry Advanced Options
  564. "geometry_toolchangexy": "0.0, 0.0",
  565. "geometry_startz": None,
  566. "geometry_feedrate_rapid": 1500,
  567. "geometry_extracut": False,
  568. "geometry_extracut_length": 0.1,
  569. "geometry_z_pdepth": -0.02,
  570. "geometry_f_plunge": False,
  571. "geometry_spindledir": 'CW',
  572. "geometry_feedrate_probe": 75,
  573. "geometry_segx": 0.0,
  574. "geometry_segy": 0.0,
  575. # Geometry Editor
  576. "geometry_editor_sel_limit": 30,
  577. "geometry_editor_milling_type": "cl",
  578. # CNC Job General
  579. "cncjob_plot": True,
  580. "cncjob_plot_kind": 'all',
  581. "cncjob_annotation": True,
  582. "cncjob_tooldia": 1.0,
  583. "cncjob_coords_type": "G90",
  584. "cncjob_coords_decimals": 4,
  585. "cncjob_fr_decimals": 2,
  586. "cncjob_steps_per_circle": 64,
  587. "cncjob_footer": False,
  588. "cncjob_line_ending": False,
  589. "cncjob_save_filters": "G-Code Files (*.nc);;G-Code Files (*.din);;G-Code Files (*.dnc);;"
  590. "G-Code Files (*.ecs);;G-Code Files (*.eia);;G-Code Files (*.fan);;"
  591. "G-Code Files (*.fgc);;G-Code Files (*.fnc);;G-Code Files (*.gc);;"
  592. "G-Code Files (*.gcd);;G-Code Files (*.gcode);;G-Code Files (*.h);;"
  593. "G-Code Files (*.hnc);;G-Code Files (*.i);;G-Code Files (*.min);;"
  594. "G-Code Files (*.mpf);;G-Code Files (*.mpr);;G-Code Files (*.cnc);;"
  595. "G-Code Files (*.ncc);;G-Code Files (*.ncg);;G-Code Files (*.ncp);;"
  596. "G-Code Files (*.ngc);;G-Code Files (*.out);;G-Code Files (*.ply);;"
  597. "G-Code Files (*.sbp);;G-Code Files (*.tap);;G-Code Files (*.xpi);;"
  598. "All Files (*.*)",
  599. # CNC Job Options
  600. "cncjob_prepend": "",
  601. "cncjob_append": "",
  602. # CNC Job Advanced Options
  603. "cncjob_toolchange_macro": "",
  604. "cncjob_toolchange_macro_enable": False,
  605. "cncjob_annotation_fontsize": 9,
  606. "cncjob_annotation_fontcolor": '#990000',
  607. # NCC Tool
  608. "tools_ncctools": "1.0, 0.5",
  609. "tools_nccorder": 'rev',
  610. "tools_nccoverlap": 40,
  611. "tools_nccmargin": 1.0,
  612. "tools_nccmethod": "seed",
  613. "tools_nccconnect": True,
  614. "tools_ncccontour": True,
  615. "tools_nccrest": False,
  616. "tools_ncc_offset_choice": False,
  617. "tools_ncc_offset_value": 0.0000,
  618. "tools_nccref": 'itself',
  619. "tools_ncc_plotting": 'normal',
  620. "tools_nccmilling_type": 'cl',
  621. "tools_ncctool_type": 'V',
  622. "tools_ncccutz": -0.05,
  623. "tools_ncctipdia": 0.1,
  624. "tools_ncctipangle": 30,
  625. "tools_nccnewdia": 1.0,
  626. # Cutout Tool
  627. "tools_cutouttooldia": 2.4,
  628. "tools_cutoutkind": "single",
  629. "tools_cutoutmargin": 0.1,
  630. "tools_cutout_z": -1.8,
  631. "tools_cutout_depthperpass": 0.6,
  632. "tools_cutout_mdepth": True,
  633. "tools_cutoutgapsize": 4,
  634. "tools_gaps_ff": "4",
  635. "tools_cutout_convexshape": False,
  636. # Paint Tool
  637. "tools_painttooldia": 0.3,
  638. "tools_paintorder": 'rev',
  639. "tools_paintoverlap": 20,
  640. "tools_paintmargin": 0.0,
  641. "tools_paintmethod": "seed",
  642. "tools_selectmethod": "all",
  643. "tools_pathconnect": True,
  644. "tools_paintcontour": True,
  645. "tools_paint_plotting": 'normal',
  646. # 2-Sided Tool
  647. "tools_2sided_mirror_axis": "X",
  648. "tools_2sided_axis_loc": "point",
  649. "tools_2sided_drilldia": 3.125,
  650. # Film Tool
  651. "tools_film_type": 'neg',
  652. "tools_film_boundary": 1.0,
  653. "tools_film_scale_stroke": 0,
  654. "tools_film_color": '#000000',
  655. "tools_film_scale_cb": False,
  656. "tools_film_scale_x_entry": 1.0,
  657. "tools_film_scale_y_entry": 1.0,
  658. "tools_film_skew_cb": False,
  659. "tools_film_skew_x_entry": 0.0,
  660. "tools_film_skew_y_entry": 0.0,
  661. "tools_film_skew_ref_radio": 'bottomleft',
  662. "tools_film_mirror_cb": False,
  663. "tools_film_mirror_axis_radio": 'none',
  664. "tools_film_file_type_radio": 'svg',
  665. "tools_film_orientation": 'p',
  666. "tools_film_pagesize": 'A4',
  667. # Panel Tool
  668. "tools_panelize_spacing_columns": 0,
  669. "tools_panelize_spacing_rows": 0,
  670. "tools_panelize_columns": 1,
  671. "tools_panelize_rows": 1,
  672. "tools_panelize_constrain": False,
  673. "tools_panelize_constrainx": 200.0,
  674. "tools_panelize_constrainy": 290.0,
  675. "tools_panelize_panel_type": 'gerber',
  676. # Calculators Tool
  677. "tools_calc_vshape_tip_dia": 0.2,
  678. "tools_calc_vshape_tip_angle": 30,
  679. "tools_calc_vshape_cut_z": 0.05,
  680. "tools_calc_electro_length": 10.0,
  681. "tools_calc_electro_width": 10.0,
  682. "tools_calc_electro_cdensity": 13.0,
  683. "tools_calc_electro_growth": 10.0,
  684. # Transform Tool
  685. "tools_transform_rotate": 90,
  686. "tools_transform_skew_x": 0.0,
  687. "tools_transform_skew_y": 0.0,
  688. "tools_transform_scale_x": 1.0,
  689. "tools_transform_scale_y": 1.0,
  690. "tools_transform_scale_link": True,
  691. "tools_transform_scale_reference": True,
  692. "tools_transform_offset_x": 0.0,
  693. "tools_transform_offset_y": 0.0,
  694. "tools_transform_mirror_reference": False,
  695. "tools_transform_mirror_point": (0, 0),
  696. # SolderPaste Tool
  697. "tools_solderpaste_tools": "1.0, 0.3",
  698. "tools_solderpaste_new": 0.3,
  699. "tools_solderpaste_z_start": 0.05,
  700. "tools_solderpaste_z_dispense": 0.1,
  701. "tools_solderpaste_z_stop": 0.05,
  702. "tools_solderpaste_z_travel": 0.1,
  703. "tools_solderpaste_z_toolchange": 1.0,
  704. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  705. "tools_solderpaste_frxy": 150,
  706. "tools_solderpaste_frz": 150,
  707. "tools_solderpaste_frz_dispense": 1.0,
  708. "tools_solderpaste_speedfwd": 300,
  709. "tools_solderpaste_dwellfwd": 1,
  710. "tools_solderpaste_speedrev": 200,
  711. "tools_solderpaste_dwellrev": 1,
  712. "tools_solderpaste_pp": 'Paste_1',
  713. # Subtract Tool
  714. "tools_sub_close_paths": True,
  715. # ###################################################################################
  716. # ################################ TOOLS 2 ##########################################
  717. # ###################################################################################
  718. # Optimal Tool
  719. "tools_opt_precision": 4,
  720. # Check Rules Tool
  721. "tools_cr_trace_size": True,
  722. "tools_cr_trace_size_val": 0.25,
  723. "tools_cr_c2c": True,
  724. "tools_cr_c2c_val": 0.25,
  725. "tools_cr_c2o": True,
  726. "tools_cr_c2o_val": 1.0,
  727. "tools_cr_s2s": True,
  728. "tools_cr_s2s_val": 0.25,
  729. "tools_cr_s2sm": True,
  730. "tools_cr_s2sm_val": 0.25,
  731. "tools_cr_s2o": True,
  732. "tools_cr_s2o_val": 1.0,
  733. "tools_cr_sm2sm": True,
  734. "tools_cr_sm2sm_val": 0.25,
  735. "tools_cr_ri": True,
  736. "tools_cr_ri_val": 0.3,
  737. "tools_cr_h2h": True,
  738. "tools_cr_h2h_val": 0.3,
  739. "tools_cr_dh": True,
  740. "tools_cr_dh_val": 0.3,
  741. # QRCode Tool
  742. "tools_qrcode_version": 1,
  743. "tools_qrcode_error": 'L',
  744. "tools_qrcode_box_size": 3,
  745. "tools_qrcode_border_size": 4,
  746. "tools_qrcode_qrdata": '',
  747. "tools_qrcode_polarity": 'pos',
  748. "tools_qrcode_rounded": 's',
  749. "tools_qrcode_fill_color": '#000000',
  750. "tools_qrcode_back_color": '#FFFFFF',
  751. "tools_qrcode_sel_limit": 330,
  752. # Copper Thieving Tool
  753. "tools_copper_thieving_clearance": 0.25,
  754. "tools_copper_thieving_margin": 1.0,
  755. "tools_copper_thieving_reference": 'itself',
  756. "tools_copper_thieving_box_type": 'rect',
  757. "tools_copper_thieving_circle_steps": 64,
  758. "tools_copper_thieving_fill_type": 'solid',
  759. "tools_copper_thieving_dots_dia": 1.0,
  760. "tools_copper_thieving_dots_spacing": 2.0,
  761. "tools_copper_thieving_squares_size": 1.0,
  762. "tools_copper_thieving_squares_spacing": 2.0,
  763. "tools_copper_thieving_lines_size": 0.25,
  764. "tools_copper_thieving_lines_spacing": 2.0,
  765. "tools_copper_thieving_rb_margin": 1.0,
  766. "tools_copper_thieving_rb_thickness": 1.0,
  767. "tools_copper_thieving_mask_clearance": 0.0,
  768. # Fiducials Tool
  769. "tools_fiducials_dia": 1.0,
  770. "tools_fiducials_margin": 1.0,
  771. "tools_fiducials_mode": 'auto',
  772. "tools_fiducials_second_pos": 'up',
  773. "tools_fiducials_type": 'circular',
  774. "tools_fiducials_line_thickness": 0.25,
  775. # Calibration Tool
  776. "tools_cal_calsource": 'object',
  777. "tools_cal_travelz": 2.0,
  778. "tools_cal_verz": 0.1,
  779. "tools_cal_zeroz": False,
  780. "tools_cal_toolchangez": 15,
  781. # Utilities
  782. # file associations
  783. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  784. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  785. 'ncg, ncp, ngc, out, plt, ply, rol, sbp, tap, xpi',
  786. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, gb0, gb1, gb2, gb3, gb4, gb5, gb6, gb7, gb8, gb9, gbd, '
  787. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  788. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  789. # Keyword list
  790. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  791. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  792. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  793. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  794. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  795. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  796. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  797. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  798. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  799. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  800. 'toolchange_xy, tooldia, use_threads, value, x, x0, x1, y, y0, y1, z_cut, '
  801. 'z_move',
  802. "script_autocompleter": True,
  803. "script_text": "",
  804. "script_plot": True,
  805. "script_source_file": "",
  806. "document_autocompleter": False,
  807. "document_text": "",
  808. "document_plot": True,
  809. "document_source_file": "",
  810. "document_font_color": '#000000',
  811. "document_sel_color": '#0055ff',
  812. "document_font_size": 6,
  813. "document_tab_size": 80,
  814. })
  815. # ############################################################
  816. # ############### Load defaults from file ####################
  817. # ############################################################
  818. self.old_defaults_found = False
  819. if user_defaults:
  820. self.load_defaults(filename='current_defaults')
  821. if self.defaults['units'] == 'MM':
  822. self.decimals = int(self.defaults['decimals_metric'])
  823. else:
  824. self.decimals = int(self.defaults['decimals_inch'])
  825. self.current_units = self.defaults['units']
  826. # #############################################################################
  827. # ##################### CREATE MULTIPROCESSING POOL ###########################
  828. # #############################################################################
  829. self.pool = Pool(processes=cpu_count())
  830. # ##########################################################################
  831. # ################## Setting the Splash Screen #############################
  832. # ##########################################################################
  833. splash_settings = QSettings("Open Source", "FlatCAM")
  834. if splash_settings.contains("splash_screen"):
  835. show_splash = splash_settings.value("splash_screen")
  836. else:
  837. splash_settings.setValue('splash_screen', 1)
  838. # This will write the setting to the platform specific storage.
  839. del splash_settings
  840. show_splash = 1
  841. if show_splash and self.cmd_line_headless != 1:
  842. splash_pix = QtGui.QPixmap('share/splash.png')
  843. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  844. # self.splash.setMask(splash_pix.mask())
  845. # move splashscreen to the current monitor
  846. desktop = QtWidgets.QApplication.desktop()
  847. screen = desktop.screenNumber(QtGui.QCursor.pos())
  848. current_screen_center = desktop.availableGeometry(screen).center()
  849. self.splash.move(current_screen_center - self.splash.rect().center())
  850. self.splash.show()
  851. self.splash.showMessage(_("FlatCAM is initializing ..."),
  852. alignment=Qt.AlignBottom | Qt.AlignLeft,
  853. color=QtGui.QColor("gray"))
  854. else:
  855. show_splash = 0
  856. # #############################################################################
  857. # ##################### Initialize GUI ########################################
  858. # #############################################################################
  859. # FlatCAM colors used in plotting
  860. self.FC_light_green = '#BBF268BF'
  861. self.FC_dark_green = '#006E20BF'
  862. self.FC_light_blue = '#a5a5ffbf'
  863. self.FC_dark_blue = '#0000ffbf'
  864. QtCore.QObject.__init__(self)
  865. self.ui = FlatCAMGUI(self)
  866. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  867. if theme_settings.contains("theme"):
  868. theme = theme_settings.value('theme', type=str)
  869. else:
  870. theme = 'white'
  871. if theme == 'white':
  872. self.cursor_color_3D = 'black'
  873. else:
  874. self.cursor_color_3D = 'gray'
  875. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  876. self.ui.final_save.connect(self.final_save)
  877. # restore the toolbar view
  878. self.restore_toolbar_view()
  879. # restore the GUI geometry
  880. self.restore_main_win_geom()
  881. # set FlatCAM units in the Status bar
  882. self.set_screen_units(self.defaults['units'])
  883. # #############################################################################
  884. # ######################## UPDATE PREFERENCES GUI FORMS #######################
  885. # #############################################################################
  886. # when adding entries here read the comments in the method found bellow named:
  887. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  888. self.defaults_form_fields = {
  889. # General App
  890. "decimals_inch": self.ui.general_defaults_form.general_app_group.precision_inch_entry,
  891. "decimals_metric": self.ui.general_defaults_form.general_app_group.precision_metric_entry,
  892. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  893. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  894. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  895. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  896. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  897. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  898. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  899. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  900. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  901. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  902. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  903. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  904. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  905. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  906. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_group.bm_limit_spinner,
  907. "global_machinist_setting": self.ui.general_defaults_form.general_app_group.machinist_cb,
  908. # General GUI Preferences
  909. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  910. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  911. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  912. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  913. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  914. "global_workspace_orientation": self.ui.general_defaults_form.general_gui_group.wk_orientation_radio,
  915. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  916. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  917. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  918. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  919. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  920. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  921. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  922. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  923. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  924. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  925. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  926. # General GUI Settings
  927. "global_theme": self.ui.general_defaults_form.general_gui_set_group.theme_radio,
  928. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  929. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  930. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  931. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  932. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  933. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  934. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  935. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  936. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  937. "global_cursor_type": self.ui.general_defaults_form.general_gui_set_group.cursor_radio,
  938. "global_cursor_size": self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry,
  939. # Gerber General
  940. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  941. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  942. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  943. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  944. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  945. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  946. # Gerber Options
  947. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  948. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  949. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  950. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  951. "gerber_iso_scope": self.ui.gerber_defaults_form.gerber_opt_group.iso_scope_radio,
  952. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  953. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  954. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  955. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  956. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  957. # Gerber Advanced Options
  958. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  959. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  960. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  961. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  962. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  963. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  964. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  965. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  966. "gerber_iso_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.iso_type_radio,
  967. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  968. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  969. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  970. # Gerber Export
  971. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  972. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  973. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  974. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  975. # Gerber Editor
  976. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  977. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  978. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  979. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  980. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  981. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  982. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  983. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  984. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  985. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  986. "gerber_editor_circ_angle":
  987. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  988. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  989. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  990. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  991. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  992. # Excellon General
  993. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  994. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  995. "excellon_format_upper_in":
  996. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  997. "excellon_format_lower_in":
  998. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  999. "excellon_format_upper_mm":
  1000. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1001. "excellon_format_lower_mm":
  1002. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1003. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  1004. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  1005. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  1006. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  1007. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  1008. # Excellon Options
  1009. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  1010. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  1011. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  1012. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  1013. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  1014. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  1015. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  1016. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  1017. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  1018. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  1019. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  1020. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  1021. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  1022. # Excellon Advanced Options
  1023. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  1024. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  1025. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  1026. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1027. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  1028. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  1029. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  1030. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  1031. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  1032. # Excellon Export
  1033. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  1034. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  1035. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  1036. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  1037. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  1038. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  1039. # Excellon Editor
  1040. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  1041. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  1042. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  1043. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  1044. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  1045. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  1046. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  1047. "excellon_editor_circ_angle":
  1048. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  1049. # Excellon Slots
  1050. "excellon_editor_slot_direction":
  1051. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  1052. "excellon_editor_slot_angle":
  1053. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  1054. "excellon_editor_slot_length":
  1055. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  1056. # Excellon Slots
  1057. "excellon_editor_slot_array_size":
  1058. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  1059. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  1060. "excellon_editor_slot_lin_pitch":
  1061. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  1062. "excellon_editor_slot_lin_angle":
  1063. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  1064. "excellon_editor_slot_circ_dir":
  1065. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  1066. "excellon_editor_slot_circ_angle":
  1067. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  1068. # Geometry General
  1069. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  1070. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  1071. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  1072. # Geometry Options
  1073. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  1074. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  1075. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  1076. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  1077. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  1078. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  1079. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  1080. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  1081. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  1082. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  1083. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  1084. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  1085. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  1086. # Geometry Advanced Options
  1087. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  1088. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  1089. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1090. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  1091. "geometry_extracut_length": self.ui.geometry_defaults_form.geometry_adv_opt_group.e_cut_entry,
  1092. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  1093. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  1094. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  1095. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  1096. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  1097. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  1098. # Geometry Editor
  1099. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  1100. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  1101. # CNCJob General
  1102. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  1103. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  1104. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  1105. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  1106. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  1107. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  1108. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  1109. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  1110. "cncjob_line_ending": self.ui.cncjob_defaults_form.cncjob_gen_group.line_ending_cb,
  1111. # CNC Job Options
  1112. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  1113. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  1114. # CNC Job Advanced Options
  1115. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  1116. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  1117. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  1118. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  1119. # NCC Tool
  1120. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  1121. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  1122. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  1123. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  1124. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  1125. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  1126. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  1127. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  1128. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  1129. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  1130. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  1131. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  1132. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  1133. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  1134. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  1135. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  1136. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  1137. "tools_nccnewdia": self.ui.tools_defaults_form.tools_ncc_group.newdia_entry,
  1138. # CutOut Tool
  1139. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  1140. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  1141. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  1142. "tools_cutout_z": self.ui.tools_defaults_form.tools_cutout_group.cutz_entry,
  1143. "tools_cutout_depthperpass": self.ui.tools_defaults_form.tools_cutout_group.maxdepth_entry,
  1144. "tools_cutout_mdepth": self.ui.tools_defaults_form.tools_cutout_group.mpass_cb,
  1145. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  1146. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  1147. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  1148. # Paint Area Tool
  1149. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  1150. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  1151. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  1152. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  1153. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  1154. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  1155. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  1156. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  1157. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  1158. # 2-sided Tool
  1159. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  1160. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  1161. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  1162. # Film Tool
  1163. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  1164. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  1165. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  1166. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  1167. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  1168. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  1169. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  1170. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  1171. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  1172. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  1173. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  1174. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  1175. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  1176. "tools_film_file_type_radio": self.ui.tools_defaults_form.tools_film_group.file_type_radio,
  1177. "tools_film_orientation": self.ui.tools_defaults_form.tools_film_group.orientation_radio,
  1178. "tools_film_pagesize": self.ui.tools_defaults_form.tools_film_group.pagesize_combo,
  1179. # Panelize Tool
  1180. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  1181. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  1182. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  1183. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  1184. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  1185. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  1186. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  1187. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  1188. # Calculators Tool
  1189. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  1190. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  1191. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  1192. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  1193. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  1194. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  1195. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  1196. # Transformations Tool
  1197. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  1198. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  1199. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  1200. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  1201. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  1202. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  1203. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  1204. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  1205. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  1206. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  1207. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  1208. # SolderPaste Dispensing Tool
  1209. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  1210. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  1211. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  1212. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  1213. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  1214. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  1215. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  1216. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  1217. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  1218. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  1219. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  1220. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  1221. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  1222. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  1223. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  1224. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  1225. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  1226. # ###################################################################################
  1227. # ################################ TOOLS 2 ##########################################
  1228. # ###################################################################################
  1229. # Optimal Tool
  1230. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  1231. # Check Rules Tool
  1232. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  1233. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  1234. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  1235. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  1236. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  1237. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  1238. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  1239. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  1240. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  1241. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  1242. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  1243. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  1244. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  1245. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  1246. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  1247. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  1248. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  1249. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  1250. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  1251. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  1252. # QRCode Tool
  1253. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  1254. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  1255. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  1256. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  1257. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  1258. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  1259. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  1260. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  1261. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  1262. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  1263. # Copper Thieving Tool
  1264. "tools_copper_thieving_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  1265. "tools_copper_thieving_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  1266. "tools_copper_thieving_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  1267. "tools_copper_thieving_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  1268. "tools_copper_thieving_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  1269. "tools_copper_thieving_fill_type": self.ui.tools2_defaults_form.tools2_cfill_group.fill_type_radio,
  1270. "tools_copper_thieving_dots_dia": self.ui.tools2_defaults_form.tools2_cfill_group.dot_dia_entry,
  1271. "tools_copper_thieving_dots_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.dot_spacing_entry,
  1272. "tools_copper_thieving_squares_size": self.ui.tools2_defaults_form.tools2_cfill_group.square_size_entry,
  1273. "tools_copper_thieving_squares_spacing":
  1274. self.ui.tools2_defaults_form.tools2_cfill_group.squares_spacing_entry,
  1275. "tools_copper_thieving_lines_size": self.ui.tools2_defaults_form.tools2_cfill_group.line_size_entry,
  1276. "tools_copper_thieving_lines_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.lines_spacing_entry,
  1277. "tools_copper_thieving_rb_margin": self.ui.tools2_defaults_form.tools2_cfill_group.rb_margin_entry,
  1278. "tools_copper_thieving_rb_thickness": self.ui.tools2_defaults_form.tools2_cfill_group.rb_thickness_entry,
  1279. "tools_copper_thieving_mask_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_ppm_entry,
  1280. # Fiducials Tool
  1281. "tools_fiducials_dia": self.ui.tools2_defaults_form.tools2_fiducials_group.dia_entry,
  1282. "tools_fiducials_margin": self.ui.tools2_defaults_form.tools2_fiducials_group.margin_entry,
  1283. "tools_fiducials_mode": self.ui.tools2_defaults_form.tools2_fiducials_group.mode_radio,
  1284. "tools_fiducials_second_pos": self.ui.tools2_defaults_form.tools2_fiducials_group.pos_radio,
  1285. "tools_fiducials_type": self.ui.tools2_defaults_form.tools2_fiducials_group.fid_type_radio,
  1286. "tools_fiducials_line_thickness": self.ui.tools2_defaults_form.tools2_fiducials_group.line_thickness_entry,
  1287. # Calibration Tool
  1288. "tools_cal_calsource": self.ui.tools2_defaults_form.tools2_cal_group.cal_source_radio,
  1289. "tools_cal_travelz": self.ui.tools2_defaults_form.tools2_cal_group.travelz_entry,
  1290. "tools_cal_verz": self.ui.tools2_defaults_form.tools2_cal_group.verz_entry,
  1291. "tools_cal_zeroz": self.ui.tools2_defaults_form.tools2_cal_group.zeroz_cb,
  1292. "tools_cal_toolchangez": self.ui.tools2_defaults_form.tools2_cal_group.toolchangez_entry,
  1293. # Utilities
  1294. # File associations
  1295. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  1296. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  1297. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  1298. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  1299. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  1300. }
  1301. # update the Preferences GUI elements with the values in the self.defaults
  1302. self.defaults_write_form()
  1303. # When the self.defaults dictionary changes will update the Preferences GUI forms
  1304. self.defaults.set_change_callback(self.on_defaults_dict_change)
  1305. # #############################################################################
  1306. # ############################## Data #########################################
  1307. # #############################################################################
  1308. self.recent = []
  1309. self.recent_projects = []
  1310. self.clipboard = QtWidgets.QApplication.clipboard()
  1311. self.project_filename = None
  1312. self.toggle_units_ignore = False
  1313. # #############################################################################
  1314. # ########################## LOAD POSTPROCESSORS ##############################
  1315. # #############################################################################
  1316. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  1317. # the preprocessor file
  1318. self.preprocessors = load_preprocessors(self)
  1319. # make sure that always the 'default' preprocessor is the first item in the dictionary
  1320. if 'default' in self.preprocessors.keys():
  1321. new_ppp_dict = dict()
  1322. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  1323. default_pp = self.preprocessors.pop('default')
  1324. new_ppp_dict['default'] = default_pp
  1325. # then add the rest of the keys
  1326. for name, val_class in self.preprocessors.items():
  1327. new_ppp_dict[name] = val_class
  1328. # and now put back the ordered dict with 'default' key first
  1329. self.preprocessors = new_ppp_dict
  1330. for name in list(self.preprocessors.keys()):
  1331. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  1332. if name.partition('_')[0] == 'Paste':
  1333. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  1334. continue
  1335. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1336. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  1337. if name == 'hpgl':
  1338. continue
  1339. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1340. # #############################################################################
  1341. # ########################## LOAD LANGUAGES ##################################
  1342. # #############################################################################
  1343. self.languages = fcTranslate.load_languages()
  1344. for name in sorted(self.languages.values()):
  1345. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  1346. # #############################################################################
  1347. # ############################ APPLY APP LANGUAGE #############################
  1348. # #############################################################################
  1349. ret_val = fcTranslate.apply_language('strings')
  1350. if ret_val == "no language":
  1351. self.inform.emit('[ERROR] %s' %
  1352. _("Could not find the Language files. The App strings are missing."))
  1353. log.debug("Could not find the Language files. The App strings are missing.")
  1354. else:
  1355. # make the current language the current selection on the language combobox
  1356. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1357. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1358. # #############################################################################
  1359. # ########################### CREATE UNIQUE SERIAL NUMBER #####################
  1360. # #############################################################################
  1361. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1362. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1363. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1364. self.save_defaults(silent=True, first_time=True)
  1365. self.propagate_defaults(silent=True)
  1366. # def auto_save_defaults():
  1367. # try:
  1368. # self.save_defaults(silent=True)
  1369. # self.propagate_defaults(silent=True)
  1370. # finally:
  1371. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1372. # the following lines activates automatic defaults save
  1373. # if user_defaults:
  1374. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1375. # #############################################################################
  1376. # ########################### UPDATE THE OPTIONS ##############################
  1377. # #############################################################################
  1378. self.options = LoudDict()
  1379. # ----------------------------------------------------------------------------------------------------
  1380. # Update the self.options from the self.defaults
  1381. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1382. # -----------------------------------------------------------------------------------------------------
  1383. # Copy app defaults to project options
  1384. for def_key, def_val in self.defaults.items():
  1385. self.options[def_key] = deepcopy(def_val)
  1386. # self.options.update(self.defaults)
  1387. self.gen_form = None
  1388. self.ger_form = None
  1389. self.exc_form = None
  1390. self.geo_form = None
  1391. self.cnc_form = None
  1392. self.tools_form = None
  1393. self.tools2_form = None
  1394. self.fa_form = None
  1395. # Will show the Preferences GUI
  1396. self.show_preferences_gui()
  1397. # Initialize the color box's color in Preferences -> Global -> Color
  1398. self.init_color_pickers_in_preferences_gui()
  1399. # ### End of Data ####
  1400. # #############################################################################
  1401. # ######################## SETUP OBJECT COLLECTION ############################
  1402. # #############################################################################
  1403. self.collection = ObjectCollection(self)
  1404. self.ui.project_tab_layout.addWidget(self.collection.view)
  1405. # ### Adjust tabs width ## ##
  1406. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1407. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1408. self.collection.view.setMinimumWidth(290)
  1409. self.log.debug("Finished creating Object Collection.")
  1410. # #############################################################################
  1411. # ############################## SETUP Plot Area ##############################
  1412. # #############################################################################
  1413. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1414. if self.defaults["global_graphic_engine"] == '3D':
  1415. self.is_legacy = False
  1416. else:
  1417. self.is_legacy = True
  1418. # Event signals disconnect id holders
  1419. self.mp = None
  1420. self.mm = None
  1421. self.mr = None
  1422. self.mdc = None
  1423. self.mp_zc = None
  1424. # Matplotlib axis
  1425. self.axes = None
  1426. if show_splash:
  1427. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1428. "Canvas initialization started."),
  1429. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1430. color=QtGui.QColor("gray"))
  1431. start_plot_time = time.time() # debug
  1432. self.plotcanvas = None
  1433. self.app_cursor = None
  1434. self.hover_shapes = None
  1435. # setup the PlotCanvas
  1436. self.on_plotcanvas_setup()
  1437. end_plot_time = time.time()
  1438. self.used_time = end_plot_time - start_plot_time
  1439. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1440. if show_splash:
  1441. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1442. "Canvas initialization started.\n"
  1443. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1444. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1445. color=QtGui.QColor("gray"))
  1446. self.ui.splitter.setStretchFactor(1, 2)
  1447. # #############################################################################
  1448. # ################################### SYS TRAY ################################
  1449. # #############################################################################
  1450. if self.defaults["global_systray_icon"]:
  1451. self.parent_w = QtWidgets.QWidget()
  1452. if self.cmd_line_headless == 1:
  1453. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1454. headless=True,
  1455. parent=self.parent_w)
  1456. else:
  1457. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1458. parent=self.parent_w)
  1459. # #############################################################################
  1460. # ################################## Worker SETUP #############################
  1461. # #############################################################################
  1462. if self.defaults["global_worker_number"]:
  1463. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1464. else:
  1465. self.workers = WorkerStack(workers_number=2)
  1466. self.worker_task.connect(self.workers.add_task)
  1467. self.log.debug("Finished creating Workers crew.")
  1468. # #############################################################################
  1469. # ################################# Activity Monitor ##########################
  1470. # #############################################################################
  1471. self.activity_view = FlatCAMActivityView(app=self)
  1472. self.ui.infobar.addWidget(self.activity_view)
  1473. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1474. # #############################################################################
  1475. # ################################## Signal handling ##########################
  1476. # #############################################################################
  1477. # ################################# Custom signals ###########################
  1478. # signal for displaying messages in status bar
  1479. self.inform.connect(self.info)
  1480. # signal to be called when the app is quiting
  1481. self.app_quit.connect(self.quit_application)
  1482. self.message.connect(self.message_dialog)
  1483. self.progress.connect(self.set_progress_bar)
  1484. # signals that are emitted when object state changes
  1485. self.object_created.connect(self.on_object_created)
  1486. self.object_changed.connect(self.on_object_changed)
  1487. self.object_plotted.connect(self.on_object_plotted)
  1488. self.plots_updated.connect(self.on_plots_updated)
  1489. # signals emitted when file state change
  1490. self.file_opened.connect(self.register_recent)
  1491. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1492. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1493. # ############# Standard signals ###################
  1494. # ### Menu
  1495. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1496. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1497. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1498. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1499. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1500. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1501. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1502. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1503. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1504. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1505. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1506. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1507. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1508. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1509. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1510. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1511. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1512. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1513. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1514. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1515. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1516. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1517. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1518. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1519. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1520. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1521. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1522. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1523. self.ui.menufile_exit.triggered.connect(self.final_save)
  1524. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1525. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1526. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1527. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1528. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1529. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1530. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1531. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1532. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1533. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1534. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1535. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1536. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1537. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1538. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1539. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1540. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1541. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1542. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1543. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1544. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1545. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1546. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1547. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1548. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1549. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1550. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1551. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1552. self.ui.menuoptions_tools_db.triggered.connect(self.on_tools_database)
  1553. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1554. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1555. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1556. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1557. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1558. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1559. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1560. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1561. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1562. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1563. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1564. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1565. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1566. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1567. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1568. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1569. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1570. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1571. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1572. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1573. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1574. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1575. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1576. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1577. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1578. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1579. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1580. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1581. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1582. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1583. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1584. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1585. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1586. # ToolBar signals
  1587. self.connect_toolbar_signals()
  1588. # Notebook and Plot Tab Area signals
  1589. # make the right click on the notebook tab and plot tab area tab raise a menu
  1590. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1591. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1592. self.on_tab_setup_context_menu()
  1593. # activate initial state
  1594. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1595. # Context Menu
  1596. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1597. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1598. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1599. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1600. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1601. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1602. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1603. self.ui.clearplot.triggered.connect(self.clear_plots)
  1604. self.ui.replot.triggered.connect(self.plot_all)
  1605. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1606. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1607. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1608. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1609. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1610. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1611. # Preferences Plot Area TAB
  1612. self.ui.pref_save_button.clicked.connect(lambda: self.on_save_button(save_to_file=True))
  1613. self.ui.pref_apply_button.clicked.connect(lambda: self.on_save_button(save_to_file=False))
  1614. self.ui.pref_close_button.clicked.connect(self.on_pref_close_button)
  1615. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1616. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1617. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1618. # #############################################################################
  1619. # ######################### GUI PREFERENCES SIGNALS ###########################
  1620. # #############################################################################
  1621. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1622. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1623. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1624. )
  1625. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1626. lambda: self.on_toggle_units(no_pref=False))
  1627. # #############################################################################
  1628. # ############################# GUI COLORS SIGNALS ############################
  1629. # #############################################################################
  1630. # Setting plot colors signals
  1631. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1632. self.on_pf_color_entry)
  1633. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1634. self.on_pf_color_button)
  1635. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1636. self.on_pf_color_spinner)
  1637. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1638. self.on_pf_color_slider)
  1639. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1640. self.on_pl_color_entry)
  1641. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1642. self.on_pl_color_button)
  1643. # Setting selection (left - right) colors signals
  1644. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1645. self.on_sf_color_entry)
  1646. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1647. self.on_sf_color_button)
  1648. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1649. self.on_sf_color_spinner)
  1650. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1651. self.on_sf_color_slider)
  1652. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1653. self.on_sl_color_entry)
  1654. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1655. self.on_sl_color_button)
  1656. # Setting selection (right - left) colors signals
  1657. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1658. self.on_alt_sf_color_entry)
  1659. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1660. self.on_alt_sf_color_button)
  1661. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1662. self.on_alt_sf_color_spinner)
  1663. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1664. self.on_alt_sf_color_slider)
  1665. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1666. self.on_alt_sl_color_entry)
  1667. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1668. self.on_alt_sl_color_button)
  1669. # Setting Editor Draw colors signals
  1670. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1671. self.on_draw_color_entry)
  1672. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1673. self.on_draw_color_button)
  1674. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1675. self.on_sel_draw_color_entry)
  1676. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1677. self.on_sel_draw_color_button)
  1678. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1679. self.on_proj_color_entry)
  1680. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1681. self.on_proj_color_button)
  1682. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1683. self.on_proj_color_dis_entry)
  1684. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1685. self.on_proj_color_dis_button)
  1686. # ############################# workspace setting signals #####################
  1687. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1688. self.ui.general_defaults_form.general_gui_group.wk_orientation_radio.activated_custom.connect(
  1689. self.on_workspace_modified
  1690. )
  1691. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1692. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1693. # #############################################################################
  1694. # ############################# GUI SETTINGS SIGNALS ##########################
  1695. # #############################################################################
  1696. self.ui.general_defaults_form.general_gui_set_group.theme_radio.activated_custom.connect(self.on_theme_change)
  1697. self.ui.general_defaults_form.general_gui_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1698. # ########## CNC Job related signals #############
  1699. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1700. self.on_cnc_custom_parameters)
  1701. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1702. self.on_annotation_fontcolor_entry)
  1703. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1704. self.on_annotation_fontcolor_button)
  1705. # ########## Tools related signals #############
  1706. # Film Tool
  1707. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1708. self.on_film_color_entry)
  1709. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1710. self.on_film_color_button)
  1711. # QRCode Tool
  1712. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1713. self.on_qrcode_fill_color_entry)
  1714. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1715. self.on_qrcode_fill_color_button)
  1716. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1717. self.on_qrcode_back_color_entry)
  1718. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1719. self.on_qrcode_back_color_button)
  1720. # portability changed signal
  1721. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1722. # Object list
  1723. self.collection.view.activated.connect(self.on_row_activated)
  1724. self.collection.item_selected.connect(self.on_row_selected)
  1725. self.object_status_changed.connect(self.on_collection_updated)
  1726. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1727. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1728. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1729. # Export Excellon parameters.
  1730. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1731. self.on_update_exc_export
  1732. )
  1733. # call it once to make sure it is updated at startup
  1734. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1735. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1736. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1737. self.on_excellon_defaults_button)
  1738. # when there are arguments at application startup this get launched
  1739. self.args_at_startup[list].connect(self.on_startup_args)
  1740. # #############################################################################
  1741. # ########################## FILE ASSOCIATIONS SIGNALS ########################
  1742. # #############################################################################
  1743. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1744. lambda: self.restore_extensions(ext_type='excellon'))
  1745. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1746. lambda: self.restore_extensions(ext_type='gcode'))
  1747. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1748. lambda: self.restore_extensions(ext_type='gerber'))
  1749. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1750. lambda: self.delete_all_extensions(ext_type='excellon'))
  1751. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1752. lambda: self.delete_all_extensions(ext_type='gcode'))
  1753. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1754. lambda: self.delete_all_extensions(ext_type='gerber'))
  1755. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1756. lambda: self.add_extension(ext_type='excellon'))
  1757. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1758. lambda: self.add_extension(ext_type='gcode'))
  1759. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1760. lambda: self.add_extension(ext_type='gerber'))
  1761. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1762. lambda: self.del_extension(ext_type='excellon'))
  1763. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1764. lambda: self.del_extension(ext_type='gcode'))
  1765. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1766. lambda: self.del_extension(ext_type='gerber'))
  1767. # connect the 'Apply' buttons from the Preferences/File Associations
  1768. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1769. lambda: self.on_register_files(obj_type='excellon'))
  1770. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1771. lambda: self.on_register_files(obj_type='gcode'))
  1772. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1773. lambda: self.on_register_files(obj_type='gerber'))
  1774. # #############################################################################
  1775. # ################################ KEYWORDS SIGNALS ###########################
  1776. # #############################################################################
  1777. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1778. lambda: self.restore_extensions(ext_type='keyword'))
  1779. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1780. lambda: self.delete_all_extensions(ext_type='keyword'))
  1781. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1782. lambda: self.add_extension(ext_type='keyword'))
  1783. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1784. lambda: self.del_extension(ext_type='keyword'))
  1785. # splash screen button signal
  1786. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1787. # connect the abort_all_tasks related slots to the related signals
  1788. self.proc_container.idle_flag.connect(self.app_is_idle)
  1789. # signal emitted when a tab is closed in the Plot Area
  1790. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1791. # #####################################################################################
  1792. # ########### FINISHED CONNECTING SIGNALS #############################################
  1793. # #####################################################################################
  1794. self.log.debug("Finished connecting Signals.")
  1795. # #####################################################################################
  1796. # ########################## Other setups #############################################
  1797. # #####################################################################################
  1798. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1799. # depending on from where those tools are called different actions can be done
  1800. self.call_source = 'app'
  1801. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1802. self.tool_tab_locked = False
  1803. # decide if to show or hide the Notebook side of the screen at startup
  1804. if self.defaults["global_project_at_startup"] is True:
  1805. self.ui.splitter.setSizes([1, 1])
  1806. else:
  1807. self.ui.splitter.setSizes([0, 1])
  1808. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1809. self.setup_obj_classes()
  1810. self.setup_component_editor()
  1811. # #####################################################################################
  1812. # ######################### Auto-complete KEYWORDS ####################################
  1813. # #####################################################################################
  1814. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1815. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1816. 'delete', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon', 'ee', 'export_exc',
  1817. 'export_gcode', 'export_gerber', 'egr', 'export_svg', 'ext', 'exteriors', 'follow',
  1818. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1819. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1820. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1821. 'mirror', 'ncc',
  1822. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1823. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1824. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1825. 'save', 'save_project',
  1826. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1827. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1828. 'version', 'write_gcode'
  1829. ]
  1830. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1831. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1832. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1833. 'axisoffset',
  1834. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1835. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1836. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1837. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1838. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1839. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1840. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1841. 'spacing_columns',
  1842. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'tooldia', 'use_threads', 'value',
  1843. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1844. ]
  1845. self.tcl_keywords = [
  1846. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1847. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1848. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1849. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1850. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1851. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1852. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1853. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1854. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1855. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1856. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1857. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1858. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1859. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1860. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1861. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1862. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1863. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1864. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1865. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1866. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1867. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1868. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1869. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1870. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1871. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1872. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1873. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1874. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1875. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1876. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1877. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1878. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1879. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1880. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1881. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1882. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1883. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1884. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1885. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1886. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1887. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1888. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1889. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1890. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1891. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1892. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1893. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1894. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1895. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1896. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1897. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1898. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1899. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1900. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1901. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1902. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1903. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1904. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1905. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1906. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1907. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1908. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1909. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1910. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1911. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1912. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1913. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1914. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1915. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1916. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1917. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1918. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1919. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1920. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1921. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1922. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1923. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1924. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1925. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1926. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1927. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1928. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1929. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1930. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1931. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1932. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1933. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1934. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1935. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1936. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1937. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1938. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1939. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1940. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1941. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1942. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1943. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1944. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1945. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1946. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1947. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1948. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1949. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1950. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1951. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1952. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1953. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1954. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1955. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1956. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1957. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1958. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1959. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1960. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1961. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1962. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1963. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1964. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1965. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1966. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1967. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1968. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1969. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1970. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1971. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1972. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1973. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1974. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1975. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1976. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1977. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1978. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1979. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1980. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1981. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1982. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1983. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1984. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1985. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1986. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1987. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1988. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1989. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1990. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1991. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1992. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1993. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1994. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1995. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1996. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1997. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1998. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1999. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  2000. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  2001. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  2002. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  2003. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  2004. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  2005. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  2006. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  2007. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  2008. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  2009. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  2010. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  2011. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  2012. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  2013. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  2014. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  2015. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  2016. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  2017. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  2018. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  2019. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  2020. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  2021. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  2022. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2023. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2024. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2025. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2026. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2027. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2028. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2029. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2030. ]
  2031. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2032. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2033. # ####################################################################################
  2034. # ####################### Shell SETUP ################################################
  2035. # ####################################################################################
  2036. # this will hold the TCL instance
  2037. self.tcl = None
  2038. self.init_tcl()
  2039. self.shell = FCShell(self, version=self.version)
  2040. self.shell._edit.set_model_data(self.myKeywords)
  2041. self.shell.setWindowIcon(self.ui.app_icon)
  2042. self.shell.setWindowTitle("FlatCAM Shell")
  2043. self.shell.resize(*self.defaults["global_shell_shape"])
  2044. self.shell.append_output("FlatCAM %s - " % self.version)
  2045. self.shell.append_output(_("Type >help< to get started\n\n"))
  2046. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2047. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2048. self.ui.shell_dock.setWidget(self.shell)
  2049. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2050. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2051. QtWidgets.QDockWidget.DockWidgetFloatable |
  2052. QtWidgets.QDockWidget.DockWidgetClosable)
  2053. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2054. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2055. if self.defaults["global_shell_at_startup"]:
  2056. self.ui.shell_dock.show()
  2057. else:
  2058. self.ui.shell_dock.hide()
  2059. # ##################################################################################
  2060. # ###################### Tools and Plugins #########################################
  2061. # ##################################################################################
  2062. self.dblsidedtool = None
  2063. self.distance_tool = None
  2064. self.distance_min_tool = None
  2065. self.panelize_tool = None
  2066. self.film_tool = None
  2067. self.paste_tool = None
  2068. self.calculator_tool = None
  2069. self.rules_tool = None
  2070. self.sub_tool = None
  2071. self.move_tool = None
  2072. self.cutout_tool = None
  2073. self.ncclear_tool = None
  2074. self.optimal_tool = None
  2075. self.paint_tool = None
  2076. self.transform_tool = None
  2077. self.properties_tool = None
  2078. self.pdf_tool = None
  2079. self.image_tool = None
  2080. self.pcb_wizard_tool = None
  2081. self.cal_exc_tool = None
  2082. self.qrcode_tool = None
  2083. self.copper_thieving_tool = None
  2084. self.fiducial_tool = None
  2085. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2086. self.install_tools()
  2087. # ##################################################################################
  2088. # ########################### SETUP RECENT ITEMS ###################################
  2089. # ##################################################################################
  2090. self.setup_recent_items()
  2091. # ##################################################################################
  2092. # ########################### BookMarks Manager ####################################
  2093. # ##################################################################################
  2094. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  2095. self.install_bookmarks()
  2096. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  2097. # ##################################################################################
  2098. # ############################## Tools Database ####################################
  2099. # ##################################################################################
  2100. self.tools_db_tab = None
  2101. # ### System Font Parsing ###
  2102. # self.f_parse = ParseFont(self)
  2103. # self.parse_system_fonts()
  2104. # #####################################################################################
  2105. # ######################## Check for updates ##########################################
  2106. # #####################################################################################
  2107. # Separate thread (Not worker)
  2108. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2109. if (self.beta is False or self.beta is None) and \
  2110. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  2111. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2112. self.thr2 = QtCore.QThread()
  2113. self.worker_task.emit({'fcn': self.version_check,
  2114. 'params': []})
  2115. self.thr2.start(QtCore.QThread.LowPriority)
  2116. # #####################################################################################
  2117. # ######################### Register files with FlatCAM; #############################
  2118. # ######################### It works only for Windows for now ########################
  2119. # #####################################################################################
  2120. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2121. self.on_register_files()
  2122. # #####################################################################################
  2123. # ###################### Variables for global usage ###################################
  2124. # #####################################################################################
  2125. # hold the App units
  2126. self.units = 'MM'
  2127. # coordinates for relative position display
  2128. self.rel_point1 = (0, 0)
  2129. self.rel_point2 = (0, 0)
  2130. # variable to store coordinates
  2131. self.pos = (0, 0)
  2132. self.pos_jump = (0, 0)
  2133. # variable to store mouse coordinates
  2134. self.mouse = [0, 0]
  2135. # decide if we have a double click or single click
  2136. self.doubleclick = False
  2137. # store here the is_dragging value
  2138. self.event_is_dragging = False
  2139. # variable to store if a command is active (then the var is not None) and which one it is
  2140. self.command_active = None
  2141. # variable to store the status of moving selection action
  2142. # None value means that it's not an selection action
  2143. # True value = a selection from left to right
  2144. # False value = a selection from right to left
  2145. self.selection_type = None
  2146. # List to store the objects that are currently loaded in FlatCAM
  2147. # This list is updated on each object creation or object delete
  2148. self.all_objects_list = list()
  2149. # List to store the objects that are selected
  2150. self.sel_objects_list = list()
  2151. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2152. self.key_modifiers = None
  2153. # Variable to hold the status of the axis
  2154. self.toggle_axis = True
  2155. # Variable to hold the status of the grid lines
  2156. self.toggle_grid_lines = True
  2157. # Variable to store the status of the fullscreen event
  2158. self.toggle_fscreen = False
  2159. # Variable to store the status of the code editor
  2160. self.toggle_codeeditor = False
  2161. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2162. self.click_noproject = False
  2163. self.cursor = None
  2164. # Variable to store the GCODE that was edited
  2165. self.gcode_edited = ""
  2166. self.text_editor_tab = None
  2167. # reference for the self.ui.code_editor
  2168. self.reference_code_editor = None
  2169. self.script_code = ''
  2170. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2171. self.preferences_changed_flag = False
  2172. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  2173. self.tools_db_changed_flag = False
  2174. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2175. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2176. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2177. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2178. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2179. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2180. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'plt', 'ply', 'rol',
  2181. 'sbp', 'tap', 'xpi']
  2182. self.svg_list = ['svg']
  2183. self.dxf_list = ['dxf']
  2184. self.pdf_list = ['pdf']
  2185. self.prj_list = ['flatprj']
  2186. self.conf_list = ['flatconfig']
  2187. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2188. # flag for polygons not cleared
  2189. self.poly_not_cleared = False
  2190. # VisPy visuals
  2191. self.isHovering = False
  2192. self.notHovering = True
  2193. # Window geometry
  2194. self.x_pos = None
  2195. self.y_pos = None
  2196. self.width = None
  2197. self.height = None
  2198. # when True, the app has to return from any thread
  2199. self.abort_flag = False
  2200. # set the value used in the Windows Title
  2201. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2202. # this holds a widget that is installed in the Plot Area when View Source option is used
  2203. self.source_editor_tab = None
  2204. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  2205. # VisPy visuals
  2206. if self.is_legacy is False:
  2207. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  2208. else:
  2209. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2210. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  2211. # ###############################################################################
  2212. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2213. # ############# It's done only once after install ###############
  2214. # ###############################################################################
  2215. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2216. fac_def_from_file = factory_file.read()
  2217. factory_defaults = json.loads(fac_def_from_file)
  2218. # if the file contain an empty dictionary then save the factory defaults into the file
  2219. if not factory_defaults:
  2220. self.save_factory_defaults(silent_message=False)
  2221. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2222. initial_lay = 'compact'
  2223. self.on_layout(lay=initial_lay)
  2224. # Set the combobox in Preferences to the current layout
  2225. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2226. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2227. factory_file.close()
  2228. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  2229. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2230. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2231. # after the first run, this object should be False
  2232. self.defaults["first_run"] = False
  2233. # ###############################################################################
  2234. # ################# ADDING FlatCAM EDITORS section ##############################
  2235. # ###############################################################################
  2236. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2237. # at the first launch of the App , the editors will not be functional.
  2238. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2239. self.exc_editor = FlatCAMExcEditor(self)
  2240. self.grb_editor = FlatCAMGrbEditor(self)
  2241. self.log.debug("Finished adding FlatCAM Editor's.")
  2242. self.set_ui_title(name=_("New Project - Not saved"))
  2243. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2244. current_platform = platform.architecture()[0]
  2245. if current_platform != '64bit':
  2246. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2247. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2248. # ###############################################################################
  2249. # ####################### Finished the CONSTRUCTOR ##############################
  2250. # ###############################################################################
  2251. App.log.debug("END of constructor. Releasing control.")
  2252. # #####################################################################################
  2253. # ########################## SHOW GUI #################################################
  2254. # #####################################################################################
  2255. # if the app is not started as headless, show it
  2256. if self.cmd_line_headless != 1:
  2257. if show_splash:
  2258. # finish the splash
  2259. self.splash.finish(self.ui)
  2260. mgui_settings = QSettings("Open Source", "FlatCAM")
  2261. if mgui_settings.contains("maximized_gui"):
  2262. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  2263. if maximized_ui is True:
  2264. self.ui.showMaximized()
  2265. else:
  2266. self.ui.show()
  2267. else:
  2268. self.ui.show()
  2269. if self.defaults["global_systray_icon"]:
  2270. self.trayIcon.show()
  2271. else:
  2272. log.warning("******************* RUNNING HEADLESS *******************")
  2273. # #####################################################################################
  2274. # ########################## START-UP ARGUMENTS #######################################
  2275. # #####################################################################################
  2276. # test if the program was started with a script as parameter
  2277. if self.cmd_line_shellvar:
  2278. try:
  2279. cnt = 0
  2280. command_tcl = 0
  2281. for i in self.cmd_line_shellvar.split(','):
  2282. if i is not None:
  2283. # noinspection PyBroadException
  2284. try:
  2285. command_tcl = eval(i)
  2286. except Exception:
  2287. command_tcl = i
  2288. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2289. cnt += 1
  2290. # if there are Windows paths then replace the path separator with a Unix like one
  2291. if sys.platform == 'win32':
  2292. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2293. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2294. except Exception as ext:
  2295. print("ERROR: ", ext)
  2296. sys.exit(2)
  2297. if self.cmd_line_shellfile:
  2298. try:
  2299. if self.ui.shell_dock.isHidden():
  2300. self.ui.shell_dock.show()
  2301. with open(self.cmd_line_shellfile, "r") as myfile:
  2302. if show_splash:
  2303. self.splash.showMessage('%s: %ssec\n%s' % (
  2304. _("Canvas initialization started.\n"
  2305. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2306. _("Executing Tcl Script ...")),
  2307. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2308. color=QtGui.QColor("gray"))
  2309. cmd_line_shellfile_text = myfile.read()
  2310. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2311. except Exception as ext:
  2312. print("ERROR: ", ext)
  2313. sys.exit(2)
  2314. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2315. # the path/file_name must be enclosed in quotes if it contain spaces
  2316. if App.args:
  2317. self.args_at_startup.emit(App.args)
  2318. if self.old_defaults_found is True:
  2319. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  2320. "Please reboot the application to update."))
  2321. self.old_defaults_found = False
  2322. @staticmethod
  2323. def copy_and_overwrite(from_path, to_path):
  2324. """
  2325. From here:
  2326. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2327. :param from_path: source path
  2328. :param to_path: destination path
  2329. :return: None
  2330. """
  2331. if os.path.exists(to_path):
  2332. shutil.rmtree(to_path)
  2333. try:
  2334. shutil.copytree(from_path, to_path)
  2335. except FileNotFoundError:
  2336. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2337. shutil.copytree(from_new_path, to_path)
  2338. def on_startup_args(self, args, silent=False):
  2339. """
  2340. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2341. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  2342. :param args: a list containing the application args at startup
  2343. :return: None
  2344. """
  2345. if args is not None:
  2346. args_to_process = args
  2347. else:
  2348. args_to_process = App.args
  2349. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2350. for argument in args_to_process:
  2351. if '.FlatPrj'.lower() in argument.lower():
  2352. try:
  2353. project_name = str(argument)
  2354. if project_name == "":
  2355. if silent is False:
  2356. self.inform.emit(_("Open cancelled."))
  2357. else:
  2358. # self.open_project(project_name)
  2359. run_from_arg = True
  2360. # self.worker_task.emit({'fcn': self.open_project,
  2361. # 'params': [project_name, run_from_arg]})
  2362. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2363. except Exception as e:
  2364. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2365. elif '.FlatConfig'.lower() in argument.lower():
  2366. try:
  2367. file_name = str(argument)
  2368. if file_name == "":
  2369. if silent is False:
  2370. self.inform.emit(_("Open Config file failed."))
  2371. else:
  2372. run_from_arg = True
  2373. # self.worker_task.emit({'fcn': self.open_config_file,
  2374. # 'params': [file_name, run_from_arg]})
  2375. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2376. except Exception as e:
  2377. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2378. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2379. try:
  2380. file_name = str(argument)
  2381. if file_name == "":
  2382. if silent is False:
  2383. self.inform.emit(_("Open Script file failed."))
  2384. else:
  2385. if silent is False:
  2386. self.on_fileopenscript(name=file_name)
  2387. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2388. self.on_filerunscript(name=file_name)
  2389. except Exception as e:
  2390. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2391. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2392. log.debug("App.on_startup_args() --> Quit event.")
  2393. sys.exit()
  2394. elif 'save'.lower() in argument.lower():
  2395. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2396. self.save_defaults()
  2397. else:
  2398. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2399. proc_arg = argument.lower()
  2400. for ext in exc_list:
  2401. proc_ext = ext.replace(' ', '')
  2402. proc_ext = '.%s' % proc_ext
  2403. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2404. file_name = str(argument)
  2405. if file_name == "":
  2406. if silent is False:
  2407. self.inform.emit(_("Open Excellon file failed."))
  2408. else:
  2409. self.on_fileopenexcellon(name=file_name)
  2410. return
  2411. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2412. for ext in gco_list:
  2413. proc_ext = ext.replace(' ', '')
  2414. proc_ext = '.%s' % proc_ext
  2415. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2416. file_name = str(argument)
  2417. if file_name == "":
  2418. if silent is False:
  2419. self.inform.emit(_("Open GCode file failed."))
  2420. else:
  2421. self.on_fileopengcode(name=file_name)
  2422. return
  2423. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2424. for ext in grb_list:
  2425. proc_ext = ext.replace(' ', '')
  2426. proc_ext = '.%s' % proc_ext
  2427. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2428. file_name = str(argument)
  2429. if file_name == "":
  2430. if silent is False:
  2431. self.inform.emit(_("Open Gerber file failed."))
  2432. else:
  2433. self.on_fileopengerber(name=file_name)
  2434. return
  2435. # if it reached here without already returning then the app was registered with a file that it does not
  2436. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2437. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2438. # for arg in args_to_process:
  2439. # if 'FlatCAM.exe' in arg:
  2440. # continue
  2441. # else:
  2442. # sys.exit(2)
  2443. def set_ui_title(self, name):
  2444. """
  2445. Sets the title of the main window.
  2446. :param name: String that store the project path and project name
  2447. :return: None
  2448. """
  2449. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2450. (self.version,
  2451. ('BETA' if self.beta else ''),
  2452. platform.architecture()[0],
  2453. self.engine,
  2454. name)
  2455. )
  2456. def on_theme_change(self, val):
  2457. t_settings = QSettings("Open Source", "FlatCAM")
  2458. t_settings.setValue('theme', val)
  2459. # This will write the setting to the platform specific storage.
  2460. del t_settings
  2461. self.on_app_restart()
  2462. def on_app_restart(self):
  2463. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2464. # be left in the SySTray
  2465. try:
  2466. self.trayIcon.hide()
  2467. except Exception:
  2468. pass
  2469. fcTranslate.restart_program(app=self)
  2470. def defaults_read_form(self):
  2471. """
  2472. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2473. :return: None
  2474. """
  2475. for option in self.defaults_form_fields:
  2476. try:
  2477. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2478. except Exception as e:
  2479. log.debug("App.defaults_read_form() --> %s" % str(e))
  2480. def defaults_write_form(self, factor=None, fl_units=None):
  2481. """
  2482. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2483. self.defaults dictionary.
  2484. :param factor: will apply a factor to the values that written in the GUI elements
  2485. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2486. :return: None
  2487. """
  2488. for option in self.defaults:
  2489. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2490. # try:
  2491. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2492. # except KeyError:
  2493. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2494. # # TODO: Rethink this?
  2495. # pass
  2496. def defaults_write_form_field(self, field, factor=None, units=None):
  2497. """
  2498. Basically it is the worker in the self.defaults_write_form()
  2499. :param field: the GUI element in Preferences GUI to be updated
  2500. :param factor: factor to be applied to the field parameter
  2501. :param units: current FLatCAM measuring units
  2502. :return: None, it updates GUI elements
  2503. """
  2504. try:
  2505. if factor is None:
  2506. if units is None:
  2507. self.defaults_form_fields[field].set_value(self.defaults[field])
  2508. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2509. self.defaults_form_fields[field].set_value(self.defaults[field])
  2510. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2511. self.defaults_form_fields[field].set_value(self.defaults[field])
  2512. else:
  2513. if units is None:
  2514. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2515. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2516. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2517. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2518. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2519. except KeyError:
  2520. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2521. # TODO: Rethink this?
  2522. pass
  2523. except AttributeError:
  2524. log.debug(field)
  2525. def clear_pool(self):
  2526. """
  2527. Clear the multiprocessing pool and calls garbage collector.
  2528. :return: None
  2529. """
  2530. self.pool.close()
  2531. self.pool = Pool()
  2532. self.pool_recreated.emit(self.pool)
  2533. gc.collect()
  2534. def install_tools(self):
  2535. """
  2536. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2537. Instantiation of the Tools classes.
  2538. The order that the tools are installed is important as they can depend on each other install position.
  2539. :return: None
  2540. """
  2541. self.dblsidedtool = DblSidedTool(self)
  2542. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2543. self.cal_exc_tool = ToolCalibration(self)
  2544. self.cal_exc_tool.install(icon=QtGui.QIcon('share/drill16.png'), pos=self.ui.menutool,
  2545. before=self.dblsidedtool.menuAction,
  2546. separator=False)
  2547. self.distance_tool = Distance(self)
  2548. self.distance_tool.install(icon=QtGui.QIcon('share/distance16.png'), pos=self.ui.menuedit,
  2549. before=self.ui.menueditorigin,
  2550. separator=False)
  2551. self.distance_min_tool = DistanceMin(self)
  2552. self.distance_min_tool.install(icon=QtGui.QIcon('share/distance_min16.png'), pos=self.ui.menuedit,
  2553. before=self.ui.menueditorigin,
  2554. separator=True)
  2555. self.panelize_tool = Panelize(self)
  2556. self.panelize_tool.install(icon=QtGui.QIcon('share/panelize16.png'))
  2557. self.film_tool = Film(self)
  2558. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2559. self.paste_tool = SolderPaste(self)
  2560. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2561. self.calculator_tool = ToolCalculator(self)
  2562. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator16.png'), separator=True)
  2563. self.sub_tool = ToolSub(self)
  2564. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2565. self.rules_tool = RulesCheck(self)
  2566. self.rules_tool.install(icon=QtGui.QIcon('share/rules32.png'), pos=self.ui.menutool, separator=False)
  2567. self.optimal_tool = ToolOptimal(self)
  2568. self.optimal_tool.install(icon=QtGui.QIcon('share/open_excellon32.png'), pos=self.ui.menutool, separator=True)
  2569. self.move_tool = ToolMove(self)
  2570. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2571. before=self.ui.menueditorigin, separator=True)
  2572. self.cutout_tool = CutOut(self)
  2573. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2574. before=self.sub_tool.menuAction)
  2575. self.ncclear_tool = NonCopperClear(self)
  2576. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2577. before=self.sub_tool.menuAction, separator=True)
  2578. self.paint_tool = ToolPaint(self)
  2579. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2580. before=self.sub_tool.menuAction, separator=True)
  2581. self.copper_thieving_tool = ToolCopperThieving(self)
  2582. self.copper_thieving_tool.install(icon=QtGui.QIcon('share/copperfill32.png'), pos=self.ui.menutool)
  2583. self.fiducial_tool = ToolFiducials(self)
  2584. self.fiducial_tool.install(icon=QtGui.QIcon('share/fiducials_32.png'), pos=self.ui.menutool)
  2585. self.qrcode_tool = QRCode(self)
  2586. self.qrcode_tool.install(icon=QtGui.QIcon('share/qrcode32.png'), pos=self.ui.menutool)
  2587. self.transform_tool = ToolTransform(self)
  2588. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2589. self.properties_tool = Properties(self)
  2590. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2591. self.pdf_tool = ToolPDF(self)
  2592. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2593. separator=True)
  2594. self.image_tool = ToolImage(self)
  2595. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2596. separator=True)
  2597. self.pcb_wizard_tool = PcbWizard(self)
  2598. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2599. self.log.debug("Tools are installed.")
  2600. def remove_tools(self):
  2601. """
  2602. Will remove all the actions in the Tool menu.
  2603. :return: None
  2604. """
  2605. for act in self.ui.menutool.actions():
  2606. self.ui.menutool.removeAction(act)
  2607. def init_tools(self):
  2608. """
  2609. Initialize the Tool tab in the notebook side of the central widget.
  2610. Remove the actions in the Tools menu.
  2611. Instantiate again the FlatCAM tools (plugins).
  2612. All this is required when changing the layout: standard, compact etc.
  2613. :return: None
  2614. """
  2615. log.debug("init_tools()")
  2616. # delete the data currently in the Tools Tab and the Tab itself
  2617. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2618. if widget is not None:
  2619. widget.deleteLater()
  2620. self.ui.notebook.removeTab(2)
  2621. # rebuild the Tools Tab
  2622. self.ui.tool_tab = QtWidgets.QWidget()
  2623. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2624. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2625. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2626. self.ui.tool_scroll_area = VerticalScrollArea()
  2627. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2628. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2629. # first remove all of them
  2630. self.remove_tools()
  2631. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2632. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2633. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2634. # third install all of them
  2635. self.install_tools()
  2636. self.log.debug("Tools are initialized.")
  2637. # def parse_system_fonts(self):
  2638. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2639. # 'params': []})
  2640. def connect_toolbar_signals(self):
  2641. """
  2642. Reconnect the signals to the actions in the toolbar.
  2643. This has to be done each time after the FlatCAM tools are removed/installed.
  2644. :return: None
  2645. """
  2646. # Toolbar
  2647. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2648. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2649. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2650. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2651. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2652. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2653. self.ui.replot_btn.triggered.connect(self.plot_all)
  2654. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2655. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2656. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2657. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2658. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2659. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2660. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2661. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2662. self.ui.copy_btn.triggered.connect(self.on_copy_object)
  2663. self.ui.delete_btn.triggered.connect(self.on_delete)
  2664. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2665. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2666. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2667. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2668. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2669. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2670. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2671. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2672. # Tools Toolbar Signals
  2673. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2674. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2675. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2676. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2677. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2678. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2679. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2680. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2681. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2682. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2683. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2684. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2685. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2686. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  2687. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  2688. def object2editor(self):
  2689. """
  2690. Send the current Geometry or Excellon object (if any) into the it's editor.
  2691. :return: None
  2692. """
  2693. self.report_usage("object2editor()")
  2694. # disable the objects menu as it may interfere with the Editors
  2695. self.ui.menuobjects.setDisabled(True)
  2696. edited_object = self.collection.get_active()
  2697. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2698. isinstance(edited_object, FlatCAMExcellon):
  2699. pass
  2700. else:
  2701. self.inform.emit('[WARNING_NOTCL] %s' %
  2702. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2703. return
  2704. if isinstance(edited_object, FlatCAMGeometry):
  2705. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2706. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2707. # we set the notebook to hidden
  2708. self.ui.splitter.setSizes([0, 1])
  2709. if edited_object.multigeo is True:
  2710. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  2711. if len(sel_rows) > 1:
  2712. self.inform.emit('[WARNING_NOTCL] %s' %
  2713. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  2714. "is not possible.\n"
  2715. "Edit only one geometry at a time."))
  2716. # determine the tool dia of the selected tool
  2717. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  2718. # now find the key in the edited_object.tools that has this tooldia
  2719. multi_tool = 1
  2720. for tool in edited_object.tools:
  2721. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2722. multi_tool = tool
  2723. break
  2724. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2725. else:
  2726. self.geo_editor.edit_fcgeometry(edited_object)
  2727. # set call source to the Editor we go into
  2728. self.call_source = 'geo_editor'
  2729. elif isinstance(edited_object, FlatCAMExcellon):
  2730. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2731. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2732. if self.ui.splitter.sizes()[0] == 0:
  2733. self.ui.splitter.setSizes([1, 1])
  2734. self.exc_editor.edit_fcexcellon(edited_object)
  2735. # set call source to the Editor we go into
  2736. self.call_source = 'exc_editor'
  2737. elif isinstance(edited_object, FlatCAMGerber):
  2738. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2739. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2740. if self.ui.splitter.sizes()[0] == 0:
  2741. self.ui.splitter.setSizes([1, 1])
  2742. self.grb_editor.edit_fcgerber(edited_object)
  2743. # set call source to the Editor we go into
  2744. self.call_source = 'grb_editor'
  2745. # make sure that we can't select another object while in Editor Mode:
  2746. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2747. self.ui.project_frame.setDisabled(True)
  2748. # delete any selection shape that might be active as they are not relevant in Editor
  2749. self.delete_selection_shape()
  2750. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2751. self.ui.plot_tab_area.protectTab(0)
  2752. self.inform.emit('[WARNING_NOTCL] %s' %
  2753. _("Editor is activated ..."))
  2754. self.should_we_save = True
  2755. def editor2object(self, cleanup=None):
  2756. """
  2757. Transfers the Geometry or Excellon from it's editor to the current object.
  2758. :return: None
  2759. """
  2760. self.report_usage("editor2object()")
  2761. # re-enable the objects menu that was disabled on entry in Editor mode
  2762. self.ui.menuobjects.setDisabled(False)
  2763. # do not update a geometry or excellon object unless it comes out of an editor
  2764. if self.call_source != 'app':
  2765. edited_obj = self.collection.get_active()
  2766. if cleanup is None:
  2767. msgbox = QtWidgets.QMessageBox()
  2768. msgbox.setText(_("Do you want to save the edited object?"))
  2769. msgbox.setWindowTitle(_("Close Editor"))
  2770. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2771. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2772. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2773. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2774. msgbox.setDefaultButton(bt_yes)
  2775. msgbox.exec_()
  2776. response = msgbox.clickedButton()
  2777. if response == bt_yes:
  2778. # clean the Tools Tab
  2779. self.ui.tool_scroll_area.takeWidget()
  2780. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2781. self.ui.notebook.setTabText(2, "Tool")
  2782. if isinstance(edited_obj, FlatCAMGeometry):
  2783. obj_type = "Geometry"
  2784. if cleanup is None:
  2785. self.geo_editor.update_fcgeometry(edited_obj)
  2786. self.geo_editor.update_options(edited_obj)
  2787. self.geo_editor.deactivate()
  2788. # update the geo object options so it is including the bounding box values
  2789. try:
  2790. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2791. edited_obj.options['xmin'] = xmin
  2792. edited_obj.options['ymin'] = ymin
  2793. edited_obj.options['xmax'] = xmax
  2794. edited_obj.options['ymax'] = ymax
  2795. except AttributeError as e:
  2796. self.inform.emit('[WARNING] %s' %
  2797. _("Object empty after edit."))
  2798. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2799. elif isinstance(edited_obj, FlatCAMGerber):
  2800. obj_type = "Gerber"
  2801. if cleanup is None:
  2802. self.grb_editor.update_fcgerber()
  2803. self.grb_editor.update_options(edited_obj)
  2804. self.grb_editor.deactivate_grb_editor()
  2805. # delete the old object (the source object) if it was an empty one
  2806. try:
  2807. if len(edited_obj.solid_geometry) == 0:
  2808. old_name = edited_obj.options['name']
  2809. self.collection.set_active(old_name)
  2810. self.collection.delete_active()
  2811. except TypeError:
  2812. # if the solid_geometry is a single Polygon the len() will not work
  2813. # in any case, falling here means that we have something in the solid_geometry, even if only
  2814. # a single Polygon, therefore we pass this
  2815. pass
  2816. # restore GUI to the Selected TAB
  2817. # Remove anything else in the GUI
  2818. self.ui.selected_scroll_area.takeWidget()
  2819. # Switch notebook to Selected page
  2820. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2821. elif isinstance(edited_obj, FlatCAMExcellon):
  2822. obj_type = "Excellon"
  2823. if cleanup is None:
  2824. self.exc_editor.update_fcexcellon(edited_obj)
  2825. self.exc_editor.update_options(edited_obj)
  2826. self.exc_editor.deactivate()
  2827. # delete the old object (the source object) if it was an empty one
  2828. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2829. old_name = edited_obj.options['name']
  2830. self.collection.set_active(old_name)
  2831. self.collection.delete_active()
  2832. # restore GUI to the Selected TAB
  2833. # Remove anything else in the GUI
  2834. self.ui.tool_scroll_area.takeWidget()
  2835. # Switch notebook to Selected page
  2836. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2837. else:
  2838. self.inform.emit('[WARNING_NOTCL] %s' %
  2839. _("Select a Gerber, Geometry or Excellon Object to update."))
  2840. return
  2841. self.inform.emit('[selected] %s %s' %
  2842. (obj_type, _("is updated, returning to App...")))
  2843. elif response == bt_no:
  2844. # clean the Tools Tab
  2845. self.ui.tool_scroll_area.takeWidget()
  2846. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2847. self.ui.notebook.setTabText(2, "Tool")
  2848. if isinstance(edited_obj, FlatCAMGeometry):
  2849. self.geo_editor.deactivate()
  2850. elif isinstance(edited_obj, FlatCAMGerber):
  2851. self.grb_editor.deactivate_grb_editor()
  2852. elif isinstance(edited_obj, FlatCAMExcellon):
  2853. self.exc_editor.deactivate()
  2854. # set focus on the project tab
  2855. else:
  2856. self.inform.emit('[WARNING_NOTCL] %s' %
  2857. _("Select a Gerber, Geometry or Excellon Object to update."))
  2858. return
  2859. edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2860. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2861. elif response == bt_cancel:
  2862. return
  2863. else:
  2864. if isinstance(edited_obj, FlatCAMGeometry):
  2865. self.geo_editor.deactivate()
  2866. elif isinstance(edited_obj, FlatCAMGerber):
  2867. self.grb_editor.deactivate_grb_editor()
  2868. elif isinstance(edited_obj, FlatCAMExcellon):
  2869. self.exc_editor.deactivate()
  2870. else:
  2871. self.inform.emit('[WARNING_NOTCL] %s' %
  2872. _("Select a Gerber, Geometry or Excellon Object to update."))
  2873. return
  2874. # if notebook is hidden we show it
  2875. if self.ui.splitter.sizes()[0] == 0:
  2876. self.ui.splitter.setSizes([1, 1])
  2877. # restore the call_source to app
  2878. self.call_source = 'app'
  2879. edited_obj.plot()
  2880. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2881. self.ui.plot_tab_area.protectTab(0)
  2882. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2883. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2884. self.ui.project_frame.setDisabled(False)
  2885. def get_last_folder(self):
  2886. """
  2887. Get the folder path from where the last file was opened.
  2888. :return: String, last opened folder path
  2889. """
  2890. return self.defaults["global_last_folder"]
  2891. def get_last_save_folder(self):
  2892. """
  2893. Get the folder path from where the last file was saved.
  2894. :return: String, last saved folder path
  2895. """
  2896. loc = self.defaults["global_last_save_folder"]
  2897. if loc is None:
  2898. loc = self.defaults["global_last_folder"]
  2899. if loc is None:
  2900. loc = os.path.dirname(__file__)
  2901. return loc
  2902. def report_usage(self, resource):
  2903. """
  2904. Increments usage counter for the given resource
  2905. in self.defaults['global_stats'].
  2906. :param resource: Name of the resource.
  2907. :return: None
  2908. """
  2909. if resource in self.defaults['global_stats']:
  2910. self.defaults['global_stats'][resource] += 1
  2911. else:
  2912. self.defaults['global_stats'][resource] = 1
  2913. def init_tcl(self):
  2914. """
  2915. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2916. :return: None
  2917. """
  2918. if hasattr(self, 'tcl') and self.tcl is not None:
  2919. # self.tcl = None
  2920. # TODO we need to clean non default variables and procedures here
  2921. # new object cannot be used here as it will not remember values created for next passes,
  2922. # because tcl was execudted in old instance of TCL
  2923. pass
  2924. else:
  2925. self.tcl = tk.Tcl()
  2926. self.setup_shell()
  2927. self.log.debug("TCL Shell has been initialized.")
  2928. # TODO: This shouldn't be here.
  2929. class TclErrorException(Exception):
  2930. """
  2931. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2932. """
  2933. pass
  2934. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2935. """
  2936. Shows a message on the FlatCAM Shell
  2937. :param msg: Message to display.
  2938. :param show: Opens the shell.
  2939. :param error: Shows the message as an error.
  2940. :param warning: Shows the message as an warning.
  2941. :param success: Shows the message as an success.
  2942. :param selected: Indicate that something was selected on canvas
  2943. :return: None
  2944. """
  2945. if show:
  2946. self.ui.shell_dock.show()
  2947. try:
  2948. if error:
  2949. self.shell.append_error(msg + "\n")
  2950. elif warning:
  2951. self.shell.append_warning(msg + "\n")
  2952. elif success:
  2953. self.shell.append_success(msg + "\n")
  2954. elif selected:
  2955. self.shell.append_selected(msg + "\n")
  2956. else:
  2957. self.shell.append_output(msg + "\n")
  2958. except AttributeError:
  2959. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2960. def raise_tcl_unknown_error(self, unknownException):
  2961. """
  2962. Raise exception if is different type than TclErrorException
  2963. this is here mainly to show unknown errors inside TCL shell console.
  2964. :param unknownException:
  2965. :return:
  2966. """
  2967. if not isinstance(unknownException, self.TclErrorException):
  2968. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2969. else:
  2970. raise unknownException
  2971. def display_tcl_error(self, error, error_info=None):
  2972. """
  2973. Escape bracket [ with '\' otherwise there is error
  2974. "ERROR: missing close-bracket" instead of real error
  2975. :param error: it may be text or exception
  2976. :param error_info: Some informations about the error
  2977. :return: None
  2978. """
  2979. if isinstance(error, Exception):
  2980. exc_type, exc_value, exc_traceback = error_info
  2981. if not isinstance(error, self.TclErrorException):
  2982. show_trace = 1
  2983. else:
  2984. show_trace = int(self.defaults['global_verbose_error_level'])
  2985. if show_trace > 0:
  2986. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2987. trc_formated = []
  2988. for a in reversed(trc):
  2989. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2990. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2991. else:
  2992. text = "%s" % error
  2993. else:
  2994. text = error
  2995. text = text.replace('[', '\\[').replace('"', '\\"')
  2996. self.tcl.eval('return -code error "%s"' % text)
  2997. def raise_tcl_error(self, text):
  2998. """
  2999. This method pass exception from python into TCL as error, so we get stacktrace and reason
  3000. :param text: text of error
  3001. :return: raise exception
  3002. """
  3003. self.display_tcl_error(text)
  3004. raise self.TclErrorException(text)
  3005. def exec_command(self, text, no_echo=False):
  3006. """
  3007. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3008. Also handles execution in separated threads
  3009. :param text: FlatCAM TclCommand with parameters
  3010. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3011. will create crashes of the _Expandable_Edit widget
  3012. :return: output if there was any
  3013. """
  3014. self.report_usage('exec_command')
  3015. result = self.exec_command_test(text, False, no_echo=no_echo)
  3016. # MS: added this method call so the geometry is updated once the TCL command is executed
  3017. # if no_plot is None:
  3018. # self.plot_all()
  3019. return result
  3020. def exec_command_test(self, text, reraise=True, no_echo=False):
  3021. """
  3022. Same as exec_command(...) with additional control over exceptions.
  3023. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3024. :param text: Input command
  3025. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  3026. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3027. will create crashes of the _Expandable_Edit widget
  3028. :return: Output from the command
  3029. """
  3030. tcl_command_string = str(text)
  3031. try:
  3032. if no_echo is False:
  3033. self.shell.open_proccessing() # Disables input box.
  3034. result = self.tcl.eval(str(tcl_command_string))
  3035. if result != 'None' and no_echo is False:
  3036. self.shell.append_output(result + '\n')
  3037. except tk.TclError as e:
  3038. # This will display more precise answer if something in TCL shell fails
  3039. result = self.tcl.eval("set errorInfo")
  3040. self.log.error("Exec command Exception: %s" % (result + '\n'))
  3041. if no_echo is False:
  3042. self.shell.append_error('ERROR: ' + result + '\n')
  3043. # Show error in console and just return or in test raise exception
  3044. if reraise:
  3045. raise e
  3046. finally:
  3047. if no_echo is False:
  3048. self.shell.close_proccessing()
  3049. pass
  3050. return result
  3051. # """
  3052. # Code below is unsused. Saved for later.
  3053. # """
  3054. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  3055. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  3056. # self.log.debug(parts)
  3057. # try:
  3058. # if parts[0] not in commands:
  3059. # self.shell.append_error("Unknown command\n")
  3060. # return
  3061. #
  3062. # #import inspect
  3063. # #inspect.getargspec(someMethod)
  3064. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  3065. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  3066. # self.shell.append_error(
  3067. # "Command %s takes %d arguments. %d given.\n" %
  3068. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  3069. # )
  3070. # return
  3071. #
  3072. # cmdfcn = commands[parts[0]]["fcn"]
  3073. # cmdconv = commands[parts[0]]["converters"]
  3074. # if len(parts) - 1 > 0:
  3075. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  3076. # else:
  3077. # retval = cmdfcn()
  3078. # retfcn = commands[parts[0]]["retfcn"]
  3079. # if retval and retfcn(retval):
  3080. # self.shell.append_output(retfcn(retval) + "\n")
  3081. #
  3082. # except Exception as e:
  3083. # #self.shell.append_error(''.join(traceback.format_exc()))
  3084. # #self.shell.append_error("?\n")
  3085. # self.shell.append_error(str(e) + "\n")
  3086. def info(self, msg):
  3087. """
  3088. Informs the user. Normally on the status bar, optionally
  3089. also on the shell.
  3090. :param msg: Text to write.
  3091. :return: None
  3092. """
  3093. # Type of message in brackets at the beginning of the message.
  3094. match = re.search("\[([^\]]+)\](.*)", msg)
  3095. if match:
  3096. level = match.group(1)
  3097. msg_ = match.group(2)
  3098. self.ui.fcinfo.set_status(str(msg_), level=level)
  3099. if level.lower() == "error":
  3100. self.shell_message(msg, error=True, show=True)
  3101. elif level.lower() == "warning":
  3102. self.shell_message(msg, warning=True, show=True)
  3103. elif level.lower() == "error_notcl":
  3104. self.shell_message(msg, error=True, show=False)
  3105. elif level.lower() == "warning_notcl":
  3106. self.shell_message(msg, warning=True, show=False)
  3107. elif level.lower() == "success":
  3108. self.shell_message(msg, success=True, show=False)
  3109. elif level.lower() == "selected":
  3110. self.shell_message(msg, selected=True, show=False)
  3111. else:
  3112. self.shell_message(msg, show=False)
  3113. else:
  3114. self.ui.fcinfo.set_status(str(msg), level="info")
  3115. # make sure that if the message is to clear the infobar with a space
  3116. # is not printed over and over on the shell
  3117. if msg != '':
  3118. self.shell_message(msg)
  3119. def restore_toolbar_view(self):
  3120. """
  3121. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3122. was saved in the defaults dictionary.
  3123. :return: None
  3124. """
  3125. tb = self.defaults["global_toolbar_view"]
  3126. if tb & 1:
  3127. self.ui.toolbarfile.setVisible(True)
  3128. else:
  3129. self.ui.toolbarfile.setVisible(False)
  3130. if tb & 2:
  3131. self.ui.toolbargeo.setVisible(True)
  3132. else:
  3133. self.ui.toolbargeo.setVisible(False)
  3134. if tb & 4:
  3135. self.ui.toolbarview.setVisible(True)
  3136. else:
  3137. self.ui.toolbarview.setVisible(False)
  3138. if tb & 8:
  3139. self.ui.toolbartools.setVisible(True)
  3140. else:
  3141. self.ui.toolbartools.setVisible(False)
  3142. if tb & 16:
  3143. self.ui.exc_edit_toolbar.setVisible(True)
  3144. else:
  3145. self.ui.exc_edit_toolbar.setVisible(False)
  3146. if tb & 32:
  3147. self.ui.geo_edit_toolbar.setVisible(True)
  3148. else:
  3149. self.ui.geo_edit_toolbar.setVisible(False)
  3150. if tb & 64:
  3151. self.ui.grb_edit_toolbar.setVisible(True)
  3152. else:
  3153. self.ui.grb_edit_toolbar.setVisible(False)
  3154. if tb & 128:
  3155. self.ui.snap_toolbar.setVisible(True)
  3156. else:
  3157. self.ui.snap_toolbar.setVisible(False)
  3158. if tb & 256:
  3159. self.ui.toolbarshell.setVisible(True)
  3160. else:
  3161. self.ui.toolbarshell.setVisible(False)
  3162. def load_defaults(self, filename):
  3163. """
  3164. Loads the aplication's default settings from current_defaults.FlatConfig into
  3165. ``self.defaults``.
  3166. :return: None
  3167. """
  3168. try:
  3169. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3170. options = f.read()
  3171. f.close()
  3172. except IOError:
  3173. self.log.error("Could not load defaults file.")
  3174. self.inform.emit('[ERROR] %s' % _("Could not load defaults file."))
  3175. # in case the defaults file can't be loaded, show all toolbars
  3176. self.defaults["global_toolbar_view"] = 511
  3177. return
  3178. try:
  3179. defaults = json.loads(options)
  3180. except Exception:
  3181. # in case the defaults file can't be loaded, show all toolbars
  3182. self.defaults["global_toolbar_view"] = 511
  3183. e = sys.exc_info()[0]
  3184. App.log.error(str(e))
  3185. self.inform.emit('[ERROR] %s' % _("Failed to parse defaults file."))
  3186. return
  3187. if 'version' not in defaults or defaults['version'] != self.defaults['version']:
  3188. for k, v in defaults.items():
  3189. if k in self.defaults:
  3190. self.defaults[k] = v
  3191. # delete old factory defaults
  3192. try:
  3193. fact_def_file_path = os.path.join(self.data_path, 'factory_defaults.FlatConfig')
  3194. os.chmod(fact_def_file_path, stat.S_IRWXO | stat.S_IWRITE | stat.S_IWGRP)
  3195. os.remove(fact_def_file_path)
  3196. # recreate a new factory defaults file and save the factory defaults data into it
  3197. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  3198. json.dump(self.defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3199. f_f_def_s.close()
  3200. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  3201. os.chmod(fact_def_file_path, S_IREAD | S_IRGRP | S_IROTH)
  3202. except Exception as e:
  3203. log.debug("App.load_defaults() -> deleting old factory defaults file -> %s" % str(e))
  3204. self.old_defaults_found = True
  3205. else:
  3206. self.defaults.update(defaults)
  3207. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3208. def on_import_preferences(self):
  3209. """
  3210. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3211. ``self.defaults``.
  3212. :return: None
  3213. """
  3214. self.report_usage("on_import_preferences")
  3215. App.log.debug("on_import_preferences()")
  3216. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3217. try:
  3218. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3219. directory=self.data_path,
  3220. filter=filter_)
  3221. except TypeError:
  3222. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3223. filter=filter_)
  3224. filename = str(filename)
  3225. if filename == "":
  3226. self.inform.emit('[WARNING_NOTCL] %s' %
  3227. _("FlatCAM preferences import cancelled."))
  3228. else:
  3229. try:
  3230. f = open(filename)
  3231. options = f.read()
  3232. f.close()
  3233. except IOError:
  3234. self.log.error("Could not load defaults file.")
  3235. self.inform.emit('[ERROR_NOTCL] %s' %
  3236. _("Could not load defaults file."))
  3237. return
  3238. try:
  3239. defaults_from_file = json.loads(options)
  3240. except Exception:
  3241. e = sys.exc_info()[0]
  3242. App.log.error(str(e))
  3243. self.inform.emit('[ERROR_NOTCL] %s' %
  3244. _("Failed to parse defaults file."))
  3245. return
  3246. self.defaults.update(defaults_from_file)
  3247. self.on_preferences_edited()
  3248. self.inform.emit('[success] %s: %s' %
  3249. (_("Imported Defaults from"), filename))
  3250. def on_export_preferences(self):
  3251. """
  3252. Save the defaults dictionary to a file.
  3253. :return: None
  3254. """
  3255. self.report_usage("on_export_preferences")
  3256. App.log.debug("on_export_preferences()")
  3257. defaults_file_content = None
  3258. self.date = str(datetime.today()).rpartition('.')[0]
  3259. self.date = ''.join(c for c in self.date if c not in ':-')
  3260. self.date = self.date.replace(' ', '_')
  3261. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3262. try:
  3263. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3264. caption=_("Export FlatCAM Preferences"),
  3265. directory=self.data_path + '/preferences_' + self.date,
  3266. filter=filter__
  3267. )
  3268. except TypeError:
  3269. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3270. filter=filter__)
  3271. filename = str(filename)
  3272. defaults_from_file = {}
  3273. if filename == "":
  3274. self.inform.emit('[WARNING_NOTCL] %s' %
  3275. _("FlatCAM preferences export cancelled."))
  3276. return
  3277. else:
  3278. try:
  3279. f = open(filename, 'w')
  3280. defaults_file_content = f.read()
  3281. f.close()
  3282. except PermissionError:
  3283. self.inform.emit('[WARNING] %s' %
  3284. _("Permission denied, saving not possible.\n"
  3285. "Most likely another app is holding the file open and not accessible."))
  3286. return
  3287. except IOError:
  3288. App.log.debug('Creating a new preferences file ...')
  3289. f = open(filename, 'w')
  3290. json.dump({}, f)
  3291. f.close()
  3292. except Exception:
  3293. e = sys.exc_info()[0]
  3294. App.log.error("Could not load defaults file.")
  3295. App.log.error(str(e))
  3296. self.inform.emit('[ERROR_NOTCL] %s' %
  3297. _("Could not load preferences file."))
  3298. return
  3299. try:
  3300. defaults_from_file = json.loads(defaults_file_content)
  3301. except Exception:
  3302. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3303. # Update options
  3304. self.defaults_read_form()
  3305. defaults_from_file.update(self.defaults)
  3306. self.propagate_defaults(silent=True)
  3307. # Save update options
  3308. try:
  3309. f = open(filename, "w")
  3310. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3311. f.close()
  3312. except Exception:
  3313. self.inform.emit('[ERROR_NOTCL] %s' %
  3314. _("Failed to write defaults to file."))
  3315. return
  3316. if self.defaults["global_open_style"] is False:
  3317. self.file_opened.emit("preferences", filename)
  3318. self.file_saved.emit("preferences", filename)
  3319. self.inform.emit('[success] %s: %s' %
  3320. (_("Exported preferences to"), filename))
  3321. def on_preferences_open_folder(self):
  3322. """
  3323. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3324. :return: None
  3325. """
  3326. self.report_usage("on_preferences_open_folder()")
  3327. if sys.platform == 'win32':
  3328. subprocess.Popen('explorer %s' % self.data_path)
  3329. elif sys.platform == 'darwin':
  3330. os.system('open "%s"' % self.data_path)
  3331. else:
  3332. subprocess.Popen(['xdg-open', self.data_path])
  3333. self.inform.emit('[success] %s' %
  3334. _("FlatCAM Preferences Folder opened."))
  3335. def save_geometry(self, x, y, width, height, notebook_width):
  3336. """
  3337. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3338. launch of the application.
  3339. :param x: X position of the main window
  3340. :param y: Y position of the main window
  3341. :param width: width of the main window
  3342. :param height: height of the main window
  3343. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3344. :return: None
  3345. """
  3346. self.defaults["global_def_win_x"] = x
  3347. self.defaults["global_def_win_y"] = y
  3348. self.defaults["global_def_win_w"] = width
  3349. self.defaults["global_def_win_h"] = height
  3350. self.defaults["global_def_notebook_width"] = notebook_width
  3351. self.save_defaults()
  3352. def restore_main_win_geom(self):
  3353. try:
  3354. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3355. self.defaults["global_def_win_y"],
  3356. self.defaults["global_def_win_w"],
  3357. self.defaults["global_def_win_h"])
  3358. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3359. except KeyError as e:
  3360. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3361. def message_dialog(self, title, message, kind="info"):
  3362. """
  3363. Builds and show a custom QMessageBox to be used in FlatCAM.
  3364. :param title: title of the QMessageBox
  3365. :param message: message to be displayed
  3366. :param kind: type of QMessageBox; will display a specific icon.
  3367. :return:
  3368. """
  3369. icon = {"info": QtWidgets.QMessageBox.Information,
  3370. "warning": QtWidgets.QMessageBox.Warning,
  3371. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3372. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3373. dlg.setText(message)
  3374. dlg.exec_()
  3375. def register_recent(self, kind, filename):
  3376. """
  3377. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3378. dictionary.
  3379. :param kind: type of file that was opened
  3380. :param filename: the path and file name for the file that was opened
  3381. :return:
  3382. """
  3383. self.log.debug("register_recent()")
  3384. self.log.debug(" %s" % kind)
  3385. self.log.debug(" %s" % filename)
  3386. record = {'kind': str(kind), 'filename': str(filename)}
  3387. if record in self.recent:
  3388. return
  3389. if record in self.recent_projects:
  3390. return
  3391. if record['kind'] == 'project':
  3392. self.recent_projects.insert(0, record)
  3393. else:
  3394. self.recent.insert(0, record)
  3395. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3396. self.recent.pop()
  3397. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3398. self.recent_projects.pop()
  3399. try:
  3400. f = open(self.data_path + '/recent.json', 'w')
  3401. except IOError:
  3402. App.log.error("Failed to open recent items file for writing.")
  3403. self.inform.emit('[ERROR_NOTCL] %s' %
  3404. _('Failed to open recent files file for writing.'))
  3405. return
  3406. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3407. f.close()
  3408. try:
  3409. fp = open(self.data_path + '/recent_projects.json', 'w')
  3410. except IOError:
  3411. App.log.error("Failed to open recent items file for writing.")
  3412. self.inform.emit('[ERROR_NOTCL] %s' %
  3413. _('Failed to open recent projects file for writing.'))
  3414. return
  3415. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3416. fp.close()
  3417. # Re-build the recent items menu
  3418. self.setup_recent_items()
  3419. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3420. """
  3421. Creates a new specialized FlatCAMObj and attaches it to the application,
  3422. this is, updates the GUI accordingly, any other records and plots it.
  3423. This method is thread-safe.
  3424. Notes:
  3425. * If the name is in use, the self.collection will modify it
  3426. when appending it to the collection. There is no need to handle
  3427. name conflicts here.
  3428. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3429. :type kind: str
  3430. :param name: Name for the object.
  3431. :type name: str
  3432. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3433. The function is called with 2 parameters: the new object and the App instance.
  3434. :type initialize: function
  3435. :param active:
  3436. :param fit:
  3437. :param plot: If to plot the resulting object
  3438. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3439. self.colleaction
  3440. :return: None
  3441. :rtype: None
  3442. """
  3443. App.log.debug("new_object()")
  3444. obj_plot = plot
  3445. obj_autoselected = autoselected
  3446. t0 = time.time() # Debug
  3447. # ## Create object
  3448. classdict = {
  3449. "gerber": FlatCAMGerber,
  3450. "excellon": FlatCAMExcellon,
  3451. "cncjob": FlatCAMCNCjob,
  3452. "geometry": FlatCAMGeometry,
  3453. "script": FlatCAMScript,
  3454. "document": FlatCAMDocument
  3455. }
  3456. App.log.debug("Calling object constructor...")
  3457. # Object creation/instantiation
  3458. obj = classdict[kind](name)
  3459. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3460. # IMPORTANT
  3461. # The key names in defaults and options dictionary's are not random:
  3462. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3463. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  3464. # copied to self.options. After that, below, depending on the type of
  3465. # object that is created, it will strip the name of the object and the underline (if the original key was
  3466. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3467. # "toolchange"
  3468. for option in self.options:
  3469. if option.find(kind + "_") == 0:
  3470. oname = option[len(kind) + 1:]
  3471. obj.options[oname] = self.options[option]
  3472. obj.isHovering = False
  3473. obj.notHovering = True
  3474. # Initialize as per user request
  3475. # User must take care to implement initialize
  3476. # in a thread-safe way as is is likely that we
  3477. # have been invoked in a separate thread.
  3478. t1 = time.time()
  3479. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3480. try:
  3481. return_value = initialize(obj, self)
  3482. except Exception as e:
  3483. msg = '[ERROR_NOTCL] %s' % \
  3484. _("An internal error has ocurred. See shell.\n")
  3485. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3486. msg += traceback.format_exc()
  3487. self.inform.emit(msg)
  3488. # if str(e) == "Empty Geometry":
  3489. # self.inform.emit("[ERROR_NOTCL] )
  3490. # else:
  3491. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3492. return "fail"
  3493. t2 = time.time()
  3494. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3495. if return_value == 'fail':
  3496. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3497. return "fail"
  3498. # Check units and convert if necessary
  3499. # This condition CAN be true because initialize() can change obj.units
  3500. if self.options["units"].upper() != obj.units.upper():
  3501. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  3502. obj.convert_units(self.options["units"])
  3503. t3 = time.time()
  3504. self.log.debug("%f seconds converting units." % (t3 - t2))
  3505. # Create the bounding box for the object and then add the results to the obj.options
  3506. # But not for Scripts or for Documents
  3507. if kind != 'document' and kind != 'script':
  3508. try:
  3509. xmin, ymin, xmax, ymax = obj.bounds()
  3510. obj.options['xmin'] = xmin
  3511. obj.options['ymin'] = ymin
  3512. obj.options['xmax'] = xmax
  3513. obj.options['ymax'] = ymax
  3514. except Exception as e:
  3515. log.warning("The object has no bounds properties. %s" % str(e))
  3516. return "fail"
  3517. # update the KeyWords list with the name of the file
  3518. self.myKeywords.append(obj.options['name'])
  3519. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3520. # Move the object to the main thread and let the app know that it is available.
  3521. obj.moveToThread(self.main_thread)
  3522. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3523. return obj
  3524. def new_excellon_object(self):
  3525. """
  3526. Creates a new, blank Excellon object.
  3527. :return: None
  3528. """
  3529. self.report_usage("new_excellon_object()")
  3530. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3531. def new_geometry_object(self):
  3532. """
  3533. Creates a new, blank and single-tool Geometry object.
  3534. :return: None
  3535. """
  3536. self.report_usage("new_geometry_object()")
  3537. def initialize(obj, app):
  3538. obj.multitool = False
  3539. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3540. def new_gerber_object(self):
  3541. """
  3542. Creates a new, blank Gerber object.
  3543. :return: None
  3544. """
  3545. self.report_usage("new_gerber_object()")
  3546. def initialize(grb_obj, app):
  3547. grb_obj.multitool = False
  3548. grb_obj.source_file = []
  3549. grb_obj.multigeo = False
  3550. grb_obj.follow = False
  3551. grb_obj.apertures = {}
  3552. grb_obj.solid_geometry = []
  3553. try:
  3554. grb_obj.options['xmin'] = 0
  3555. grb_obj.options['ymin'] = 0
  3556. grb_obj.options['xmax'] = 0
  3557. grb_obj.options['ymax'] = 0
  3558. except KeyError:
  3559. pass
  3560. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3561. def new_script_object(self, name=None, text=None):
  3562. """
  3563. Creates a new, blank TCL Script object.
  3564. :param name: a name for the new object
  3565. :param text: pass a source file to the newly created script to be loaded in it
  3566. :return: None
  3567. """
  3568. self.report_usage("new_script_object()")
  3569. if text is not None:
  3570. new_source_file = text
  3571. else:
  3572. commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  3573. "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n"\
  3574. "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  3575. "ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n"\
  3576. "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  3577. "ListSys, MillDrills,\n"\
  3578. "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  3579. "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"\
  3580. "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  3581. "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  3582. "# SubtractRectangle, Version, WriteGCode\n"
  3583. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  3584. '# %s:\n' % _('TCL Tutorial is here') + \
  3585. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  3586. '# %s:\n' % _("FlatCAM commands list")
  3587. new_source_file += commands_list + '\n'
  3588. def initialize(obj, app):
  3589. obj.source_file = deepcopy(new_source_file)
  3590. if name is None:
  3591. outname = 'new_script'
  3592. else:
  3593. outname = name
  3594. self.new_object('script', outname, initialize, plot=False)
  3595. def new_document_object(self):
  3596. """
  3597. Creates a new, blank Document object.
  3598. :return: None
  3599. """
  3600. self.report_usage("new_document_object()")
  3601. def initialize(obj, app):
  3602. obj.source_file = ""
  3603. self.new_object('document', 'new_document', initialize, plot=False)
  3604. def on_object_created(self, obj, plot, auto_select):
  3605. """
  3606. Event callback for object creation.
  3607. It will add the new object to the collection. After that it will plot the object in a threaded way
  3608. :param obj: The newly created FlatCAM object.
  3609. :param plot: if the newly create object t obe plotted
  3610. :param auto_select: if the newly created object to be autoselected after creation
  3611. :return: None
  3612. """
  3613. t0 = time.time() # DEBUG
  3614. self.log.debug("on_object_created()")
  3615. # The Collection might change the name if there is a collision
  3616. self.collection.append(obj)
  3617. # after adding the object to the collection always update the list of objects that are in the collection
  3618. self.all_objects_list = self.collection.get_list()
  3619. # self.inform.emit('[selected] %s created & selected: %s' %
  3620. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3621. if obj.kind == 'gerber':
  3622. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3623. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3624. elif obj.kind == 'excellon':
  3625. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3626. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3627. elif obj.kind == 'cncjob':
  3628. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3629. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3630. elif obj.kind == 'geometry':
  3631. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3632. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3633. elif obj.kind == 'script':
  3634. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3635. kind=obj.kind.capitalize(), color='orange', name=str(obj.options['name'])))
  3636. elif obj.kind == 'document':
  3637. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3638. kind=obj.kind.capitalize(), color='darkCyan', name=str(obj.options['name'])))
  3639. # update the SHELL auto-completer model with the name of the new object
  3640. self.shell._edit.set_model_data(self.myKeywords)
  3641. if auto_select:
  3642. # select the just opened object but deselect the previous ones
  3643. self.collection.set_all_inactive()
  3644. self.collection.set_active(obj.options["name"])
  3645. else:
  3646. self.collection.set_all_inactive()
  3647. # here it is done the object plotting
  3648. def worker_task(t_obj):
  3649. with self.proc_container.new(_("Plotting")):
  3650. if isinstance(t_obj, FlatCAMCNCjob):
  3651. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3652. else:
  3653. t_obj.plot()
  3654. t1 = time.time() # DEBUG
  3655. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3656. self.object_plotted.emit(t_obj)
  3657. # Send to worker
  3658. # self.worker.add_task(worker_task, [self])
  3659. if plot is True:
  3660. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3661. def on_object_changed(self, obj):
  3662. """
  3663. Called whenever the geometry of the object was changed in some way.
  3664. This require the update of it's bounding values so it can be the selected on canvas.
  3665. Update the bounding box data from obj.options
  3666. :param obj: the object that was changed
  3667. :return: None
  3668. """
  3669. xmin, ymin, xmax, ymax = obj.bounds()
  3670. obj.options['xmin'] = xmin
  3671. obj.options['ymin'] = ymin
  3672. obj.options['xmax'] = xmax
  3673. obj.options['ymax'] = ymax
  3674. log.debug("Object changed, updating the bounding box data on self.options")
  3675. # delete the old selection shape
  3676. self.delete_selection_shape()
  3677. self.should_we_save = True
  3678. def on_object_plotted(self):
  3679. """
  3680. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3681. :return: None
  3682. """
  3683. self.on_zoom_fit(None)
  3684. def on_about(self):
  3685. """
  3686. Displays the "about" dialog found in the Menu --> Help.
  3687. :return: None
  3688. """
  3689. self.report_usage("on_about")
  3690. version = self.version
  3691. version_date = self.version_date
  3692. beta = self.beta
  3693. class AboutDialog(QtWidgets.QDialog):
  3694. def __init__(self, parent=None):
  3695. QtWidgets.QDialog.__init__(self, parent)
  3696. # Icon and title
  3697. self.setWindowIcon(parent.app_icon)
  3698. self.setWindowTitle(_("About FlatCAM"))
  3699. self.resize(600, 200)
  3700. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3701. # self.setStyleSheet(
  3702. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3703. # "background-attachment: fixed"
  3704. # )
  3705. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3706. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3707. # palette = QtGui.QPalette()
  3708. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3709. # self.setPalette(palette)
  3710. logo = QtWidgets.QLabel()
  3711. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3712. title = QtWidgets.QLabel(
  3713. "<font size=8><B>FlatCAM</B></font><BR>"
  3714. "{title}<BR>"
  3715. "<BR>"
  3716. "<BR>"
  3717. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3718. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3719. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3720. "<B>{issue}</B></a><BR>".format(
  3721. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3722. devel=_("Development"),
  3723. down=_("DOWNLOAD"),
  3724. issue=_("Issue tracker"))
  3725. )
  3726. title.setOpenExternalLinks(True)
  3727. closebtn = QtWidgets.QPushButton(_("Close"))
  3728. tab_widget = QtWidgets.QTabWidget()
  3729. description_label = QtWidgets.QLabel(
  3730. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3731. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3732. version=version,
  3733. beta=('BETA' if beta else ''),
  3734. date=version_date,
  3735. arch=platform.architecture()[0])
  3736. )
  3737. description_label.setOpenExternalLinks(True)
  3738. lic_lbl_header = QtWidgets.QLabel(
  3739. '%s:<br>%s<br>' % (
  3740. _('Licensed under the MIT license'),
  3741. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3742. "http://www.opensource.org/licenses/mit-license.php</a>"
  3743. )
  3744. )
  3745. lic_lbl_header.setOpenExternalLinks(True)
  3746. lic_lbl_body = QtWidgets.QLabel(
  3747. _(
  3748. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3749. 'of this software and associated documentation files (the "Software"), to deal\n'
  3750. 'in the Software without restriction, including without limitation the rights\n'
  3751. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3752. 'copies of the Software, and to permit persons to whom the Software is\n'
  3753. 'furnished to do so, subject to the following conditions:\n\n'
  3754. 'The above copyright notice and this permission notice shall be included in\n'
  3755. 'all copies or substantial portions of the Software.\n\n'
  3756. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3757. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3758. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3759. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3760. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3761. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3762. 'THE SOFTWARE.'
  3763. )
  3764. )
  3765. attributions_label = QtWidgets.QLabel(
  3766. _(
  3767. 'Some of the icons used are from the following sources:<br>'
  3768. '<div>Icons made by <a href="https://www.flaticon.com/authors/freepik" '
  3769. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3770. 'title="Flaticon">www.flaticon.com</a></div>'
  3771. 'Icons by <a target="_blank" href="https://icons8.com">Icons8</a>'
  3772. )
  3773. )
  3774. # layouts
  3775. layout1 = QtWidgets.QVBoxLayout()
  3776. layout1_1 = QtWidgets.QHBoxLayout()
  3777. layout1_2 = QtWidgets.QHBoxLayout()
  3778. layout2 = QtWidgets.QHBoxLayout()
  3779. layout3 = QtWidgets.QHBoxLayout()
  3780. self.setLayout(layout1)
  3781. layout1.addLayout(layout1_1)
  3782. layout1.addLayout(layout1_2)
  3783. layout1.addLayout(layout2)
  3784. layout1.addLayout(layout3)
  3785. layout1_1.addStretch()
  3786. layout1_1.addWidget(description_label)
  3787. layout1_2.addWidget(tab_widget)
  3788. self.splash_tab = QtWidgets.QWidget()
  3789. self.splash_tab.setObjectName("splash_about")
  3790. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3791. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3792. tab_widget.addTab(self.splash_tab, _("Splash"))
  3793. self.programmmers_tab = QtWidgets.QWidget()
  3794. self.programmmers_tab.setObjectName("programmers_about")
  3795. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3796. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3797. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3798. self.translators_tab = QtWidgets.QWidget()
  3799. self.translators_tab.setObjectName("translators_about")
  3800. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3801. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3802. tab_widget.addTab(self.translators_tab, _("Translators"))
  3803. self.license_tab = QtWidgets.QWidget()
  3804. self.license_tab.setObjectName("license_about")
  3805. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3806. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3807. tab_widget.addTab(self.license_tab, _("License"))
  3808. self.attributions_tab = QtWidgets.QWidget()
  3809. self.attributions_tab.setObjectName("attributions_about")
  3810. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3811. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3812. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3813. self.splash_tab_layout.addWidget(logo, stretch=0)
  3814. self.splash_tab_layout.addWidget(title, stretch=1)
  3815. pal = QtGui.QPalette()
  3816. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3817. self.prog_grid_lay = QtWidgets.QGridLayout()
  3818. self.prog_grid_lay.setHorizontalSpacing(20)
  3819. self.prog_grid_lay.setColumnStretch(0, 0)
  3820. self.prog_grid_lay.setColumnStretch(2, 1)
  3821. prog_widget = QtWidgets.QWidget()
  3822. prog_widget.setLayout(self.prog_grid_lay)
  3823. prog_scroll = QtWidgets.QScrollArea()
  3824. prog_scroll.setWidget(prog_widget)
  3825. prog_scroll.setWidgetResizable(True)
  3826. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3827. prog_scroll.setPalette(pal)
  3828. self.programmmers_tab_layout.addWidget(prog_scroll)
  3829. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3830. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3831. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3832. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3833. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  3834. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  3835. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3836. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3837. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3838. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  3839. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  3840. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  3841. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  3842. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  3843. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  3844. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  3845. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  3846. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  3847. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  3848. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  3849. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  3850. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  3851. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  3852. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  3853. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  3854. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  3855. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  3856. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  3857. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  3858. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  3859. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  3860. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  3861. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  3862. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  3863. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  3864. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 28, 0)
  3865. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 29, 0)
  3866. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 30, 0)
  3867. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 31, 0)
  3868. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 32, 0)
  3869. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 33, 0)
  3870. self.translator_grid_lay = QtWidgets.QGridLayout()
  3871. self.translator_grid_lay.setColumnStretch(0, 0)
  3872. self.translator_grid_lay.setColumnStretch(1, 0)
  3873. self.translator_grid_lay.setColumnStretch(2, 1)
  3874. self.translator_grid_lay.setColumnStretch(3, 0)
  3875. # trans_widget = QtWidgets.QWidget()
  3876. # trans_widget.setLayout(self.translator_grid_lay)
  3877. # self.translators_tab_layout.addWidget(trans_widget)
  3878. # self.translators_tab_layout.addStretch()
  3879. trans_widget = QtWidgets.QWidget()
  3880. trans_widget.setLayout(self.translator_grid_lay)
  3881. trans_scroll = QtWidgets.QScrollArea()
  3882. trans_scroll.setWidget(trans_widget)
  3883. trans_scroll.setWidgetResizable(True)
  3884. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3885. trans_scroll.setPalette(pal)
  3886. self.translators_tab_layout.addWidget(trans_scroll)
  3887. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3888. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3889. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  3890. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  3891. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  3892. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3893. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  3894. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3895. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 2, 1)
  3896. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 2, 2)
  3897. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  3898. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3899. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3900. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt"), 3, 2)
  3901. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  3902. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3903. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3904. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  3905. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3906. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3907. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  3908. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3909. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  3910. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 6, 2)
  3911. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  3912. self.translator_grid_lay.setColumnStretch(0, 0)
  3913. self.translators_tab_layout.addStretch()
  3914. self.license_tab_layout.addWidget(lic_lbl_header)
  3915. self.license_tab_layout.addWidget(lic_lbl_body)
  3916. self.license_tab_layout.addStretch()
  3917. self.attributions_tab_layout.addWidget(attributions_label)
  3918. self.attributions_tab_layout.addStretch()
  3919. layout3.addStretch()
  3920. layout3.addWidget(closebtn)
  3921. closebtn.clicked.connect(self.accept)
  3922. AboutDialog(self.ui).exec_()
  3923. def install_bookmarks(self, book_dict=None):
  3924. """
  3925. Install the bookmarks actions in the Help menu -> Bookmarks
  3926. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  3927. :return: None
  3928. """
  3929. if book_dict is None:
  3930. self.defaults["global_bookmarks"].update(
  3931. {
  3932. '1': ['FlatCAM', "http://flatcam.org"],
  3933. '2': ['Backup Site', ""]
  3934. }
  3935. )
  3936. else:
  3937. self.defaults["global_bookmarks"].clear()
  3938. self.defaults["global_bookmarks"].update(book_dict)
  3939. # first try to disconnect if somehow they get connected from elsewhere
  3940. for act in self.ui.menuhelp_bookmarks.actions():
  3941. try:
  3942. act.triggered.disconnect()
  3943. except TypeError:
  3944. pass
  3945. # clear all actions except the last one who is the Bookmark manager
  3946. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  3947. pass
  3948. else:
  3949. self.ui.menuhelp_bookmarks.removeAction(act)
  3950. bm_limit = int(self.defaults["global_bookmarks_limit"])
  3951. if self.defaults["global_bookmarks"]:
  3952. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  3953. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  3954. # the JSON is first making the keys as strings (therefore I have to use strings too
  3955. # or do the conversion :(
  3956. # )
  3957. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  3958. # the '10' entry jsut after '1' therefore ordering as strings
  3959. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  3960. key=lambda x: int(x[0]))
  3961. for entry, bookmark in sorted_bookmarks:
  3962. title = bookmark[0]
  3963. weblink = bookmark[1]
  3964. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  3965. act.setText(title)
  3966. act.setIcon(QtGui.QIcon('share/link16.png'))
  3967. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  3968. if title == 'Backup Site' and weblink == "":
  3969. act.triggered.connect(self.on_backup_site)
  3970. else:
  3971. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  3972. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  3973. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  3974. def on_bookmarks_manager(self):
  3975. """
  3976. Adds the bookmark manager in a Tab in Plot Area
  3977. :return:
  3978. """
  3979. for idx in range(self.ui.plot_tab_area.count()):
  3980. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  3981. # there can be only one instance of Bookmark Manager at one time
  3982. return
  3983. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  3984. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  3985. # add the tab if it was closed
  3986. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  3987. # delete the absolute and relative position and messages in the infobar
  3988. self.ui.position_label.setText("")
  3989. self.ui.rel_position_label.setText("")
  3990. # Switch plot_area to preferences page
  3991. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  3992. @staticmethod
  3993. def on_backup_site():
  3994. msgbox = QtWidgets.QMessageBox()
  3995. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  3996. "1. FlatCAM.org website is down\n"
  3997. "2. Someone forked FlatCAM project and wants to point\n"
  3998. "to his own website\n\n"
  3999. "If you can't get any informations about FlatCAM beta\n"
  4000. "use the YouTube channel link from the Help menu."))
  4001. msgbox.setWindowTitle(_("Alternative website"))
  4002. msgbox.setWindowIcon(QtGui.QIcon('share/globe16.png'))
  4003. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  4004. msgbox.setDefaultButton(bt_yes)
  4005. msgbox.exec_()
  4006. # response = msgbox.clickedButton()
  4007. def on_file_savedefaults(self):
  4008. """
  4009. Callback for menu item File->Save Defaults. Saves application default options
  4010. ``self.defaults`` to current_defaults.FlatConfig.
  4011. :return: None
  4012. """
  4013. self.save_defaults()
  4014. # def on_app_exit(self):
  4015. # self.report_usage("on_app_exit()")
  4016. #
  4017. # if self.collection.get_list():
  4018. # msgbox = QtWidgets.QMessageBox()
  4019. # # msgbox.setText("<B>Save changes ...</B>")
  4020. # msgbox.setText("There are files/objects opened in FlatCAM. "
  4021. # "\n"
  4022. # "Do you want to Save the project?")
  4023. # msgbox.setWindowTitle("Save changes")
  4024. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4025. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  4026. # QtWidgets.QMessageBox.Cancel)
  4027. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  4028. #
  4029. # response = msgbox.exec_()
  4030. #
  4031. # if response == QtWidgets.QMessageBox.Yes:
  4032. # self.on_file_saveprojectas(thread=False)
  4033. # elif response == QtWidgets.QMessageBox.Cancel:
  4034. # return
  4035. # self.save_defaults()
  4036. # else:
  4037. # self.save_defaults()
  4038. # log.debug("Application defaults saved ... Exit event.")
  4039. # QtWidgets.qApp.quit()
  4040. def save_defaults(self, silent=False, data_path=None, first_time=False):
  4041. """
  4042. Saves application default options
  4043. ``self.defaults`` to current_defaults.FlatConfig file.
  4044. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  4045. used at the next launch of the application.
  4046. :param silent: whether to display a message in status bar or not; boolean
  4047. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  4048. When the application is portable it should be a mobile location.
  4049. :return: None
  4050. """
  4051. self.report_usage("save_defaults")
  4052. if data_path is None:
  4053. data_path = self.data_path
  4054. # Read options from file
  4055. try:
  4056. f = open(data_path + "/current_defaults.FlatConfig")
  4057. defaults_file_content = f.read()
  4058. f.close()
  4059. except Exception:
  4060. e = sys.exc_info()[0]
  4061. App.log.error("Could not load defaults file.")
  4062. App.log.error(str(e))
  4063. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  4064. return
  4065. try:
  4066. defaults = json.loads(defaults_file_content)
  4067. except Exception:
  4068. e = sys.exc_info()[0]
  4069. App.log.error("Failed to parse defaults file.")
  4070. App.log.error(str(e))
  4071. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  4072. return
  4073. # Update options
  4074. self.defaults_read_form()
  4075. defaults.update(self.defaults)
  4076. self.propagate_defaults(silent=True)
  4077. # Save the toolbar view
  4078. tb_status = 0
  4079. if self.ui.toolbarfile.isVisible():
  4080. tb_status += 1
  4081. if self.ui.toolbargeo.isVisible():
  4082. tb_status += 2
  4083. if self.ui.toolbarview.isVisible():
  4084. tb_status += 4
  4085. if self.ui.toolbartools.isVisible():
  4086. tb_status += 8
  4087. if self.ui.exc_edit_toolbar.isVisible():
  4088. tb_status += 16
  4089. if self.ui.geo_edit_toolbar.isVisible():
  4090. tb_status += 32
  4091. if self.ui.grb_edit_toolbar.isVisible():
  4092. tb_status += 64
  4093. if self.ui.snap_toolbar.isVisible():
  4094. tb_status += 128
  4095. if self.ui.toolbarshell.isVisible():
  4096. tb_status += 256
  4097. if first_time is False:
  4098. self.defaults["global_toolbar_view"] = tb_status
  4099. # Save update options
  4100. try:
  4101. f = open(data_path + "/current_defaults.FlatConfig", "w")
  4102. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  4103. f.close()
  4104. except Exception as e:
  4105. log.debug("App.save_defaults() --> %s" % str(e))
  4106. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write defaults to file."))
  4107. return
  4108. if not silent:
  4109. self.inform.emit('[success] %s' % _("Preferences saved."))
  4110. def save_factory_defaults(self, silent_message=False, data_path=None):
  4111. """
  4112. Saves application factory default options
  4113. ``self.defaults`` to factory_defaults.FlatConfig.
  4114. It's a one time job done just after the first install.
  4115. :param silent_message: whether to display a message in status bar or not; boolean
  4116. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  4117. When the application is portable it should be a mobile location.
  4118. :return: None
  4119. """
  4120. self.report_usage("save_factory_defaults")
  4121. if data_path is None:
  4122. data_path = self.data_path
  4123. # Read options from file
  4124. try:
  4125. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  4126. factory_defaults_file_content = f_f_def.read()
  4127. f_f_def.close()
  4128. except Exception:
  4129. e = sys.exc_info()[0]
  4130. App.log.error("Could not load factory defaults file.")
  4131. App.log.error(str(e))
  4132. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  4133. return
  4134. try:
  4135. factory_defaults = json.loads(factory_defaults_file_content)
  4136. except Exception:
  4137. e = sys.exc_info()[0]
  4138. App.log.error("Failed to parse factory defaults file.")
  4139. App.log.error(str(e))
  4140. if silent_message is False:
  4141. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  4142. return
  4143. # Update options
  4144. self.defaults_read_form()
  4145. factory_defaults.update(self.defaults)
  4146. self.propagate_defaults(silent=True)
  4147. # Save update options
  4148. try:
  4149. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4150. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4151. f_f_def_s.close()
  4152. except Exception as e:
  4153. log.debug("App.save_factory_default() save update --> %s" % str(e))
  4154. if silent_message is False:
  4155. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write factory defaults to file."))
  4156. return
  4157. if silent_message is False:
  4158. self.inform.emit(_("Factory defaults saved."))
  4159. def final_save(self):
  4160. """
  4161. Callback for doing a preferences save to file whenever the application is about to quit.
  4162. If the project has changes, it will ask the user to save the project.
  4163. :return: None
  4164. """
  4165. if self.save_in_progress:
  4166. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  4167. return
  4168. if self.should_we_save and self.collection.get_list():
  4169. msgbox = QtWidgets.QMessageBox()
  4170. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4171. "\n"
  4172. "Do you want to Save the project?"))
  4173. msgbox.setWindowTitle(_("Save changes"))
  4174. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4175. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4176. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4177. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4178. msgbox.setDefaultButton(bt_yes)
  4179. msgbox.exec_()
  4180. response = msgbox.clickedButton()
  4181. if response == bt_yes:
  4182. try:
  4183. self.trayIcon.hide()
  4184. except Exception:
  4185. pass
  4186. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4187. elif response == bt_no:
  4188. try:
  4189. self.trayIcon.hide()
  4190. except Exception:
  4191. pass
  4192. self.quit_application()
  4193. elif response == bt_cancel:
  4194. return
  4195. else:
  4196. try:
  4197. self.trayIcon.hide()
  4198. except Exception:
  4199. pass
  4200. self.quit_application()
  4201. def quit_application(self):
  4202. """
  4203. Called (as a pyslot or not) when the application is quit.
  4204. :return: None
  4205. """
  4206. self.save_defaults()
  4207. log.debug("App.final_save() --> App Defaults saved.")
  4208. if self.cmd_line_headless != 1:
  4209. # save app state to file
  4210. stgs = QSettings("Open Source", "FlatCAM")
  4211. stgs.setValue('saved_gui_state', self.ui.saveState())
  4212. stgs.setValue('maximized_gui', self.ui.isMaximized())
  4213. stgs.setValue(
  4214. 'language',
  4215. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  4216. )
  4217. stgs.setValue(
  4218. 'notebook_font_size',
  4219. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4220. )
  4221. stgs.setValue(
  4222. 'axis_font_size',
  4223. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4224. )
  4225. stgs.setValue(
  4226. 'textbox_font_size',
  4227. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  4228. )
  4229. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4230. stgs.setValue(
  4231. 'machinist',
  4232. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  4233. )
  4234. # This will write the setting to the platform specific storage.
  4235. del stgs
  4236. log.debug("App.final_save() --> App UI state saved.")
  4237. QtWidgets.qApp.quit()
  4238. def on_portable_checked(self, state):
  4239. """
  4240. Callback called when the checkbox in Preferences GUI is checked.
  4241. It will set the application as portable by creating the preferences and recent files in the
  4242. 'config' folder found in the FlatCAM installation folder.
  4243. :param state: boolean, the state of the checkbox when clicked/checked
  4244. :return:
  4245. """
  4246. line_no = 0
  4247. data = None
  4248. if sys.platform != 'win32':
  4249. # this won't work in Linux or MacOS
  4250. return
  4251. # test if the app was frozen and choose the path for the configuration file
  4252. if getattr(sys, "frozen", False) is True:
  4253. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4254. else:
  4255. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4256. config_file = current_data_path + '\\configuration.txt'
  4257. try:
  4258. with open(config_file, 'r') as f:
  4259. try:
  4260. data = f.readlines()
  4261. except Exception as e:
  4262. log.debug('App.__init__() -->%s' % str(e))
  4263. return
  4264. except FileNotFoundError:
  4265. pass
  4266. for line in data:
  4267. line = line.strip('\n')
  4268. param = str(line).rpartition('=')
  4269. if param[0] == 'portable':
  4270. break
  4271. line_no += 1
  4272. if state:
  4273. data[line_no] = 'portable=True\n'
  4274. # create the new defauults files
  4275. # create current_defaults.FlatConfig file if there is none
  4276. try:
  4277. f = open(current_data_path + '/current_defaults.FlatConfig')
  4278. f.close()
  4279. except IOError:
  4280. App.log.debug('Creating empty current_defaults.FlatConfig')
  4281. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4282. json.dump({}, f)
  4283. f.close()
  4284. # create factory_defaults.FlatConfig file if there is none
  4285. try:
  4286. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4287. f.close()
  4288. except IOError:
  4289. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4290. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4291. json.dump({}, f)
  4292. f.close()
  4293. try:
  4294. f = open(current_data_path + '/recent.json')
  4295. f.close()
  4296. except IOError:
  4297. App.log.debug('Creating empty recent.json')
  4298. f = open(current_data_path + '/recent.json', 'w')
  4299. json.dump([], f)
  4300. f.close()
  4301. try:
  4302. fp = open(current_data_path + '/recent_projects.json')
  4303. fp.close()
  4304. except IOError:
  4305. App.log.debug('Creating empty recent_projects.json')
  4306. fp = open(current_data_path + '/recent_projects.json', 'w')
  4307. json.dump([], fp)
  4308. fp.close()
  4309. # save the current defaults to the new defaults file
  4310. self.save_defaults(silent=True, data_path=current_data_path)
  4311. self.save_factory_defaults(silent_message=True, data_path=current_data_path)
  4312. else:
  4313. data[line_no] = 'portable=False\n'
  4314. with open(config_file, 'w') as f:
  4315. f.writelines(data)
  4316. def on_toggle_shell(self):
  4317. """
  4318. Toggle shell: if is visible close it, if it is closed then open it
  4319. :return: None
  4320. """
  4321. self.report_usage("on_toggle_shell()")
  4322. if self.ui.shell_dock.isVisible():
  4323. self.ui.shell_dock.hide()
  4324. else:
  4325. self.ui.shell_dock.show()
  4326. def on_register_files(self, obj_type=None):
  4327. """
  4328. Called whenever there is a need to register file extensions with FlatCAM.
  4329. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4330. :param obj_type: the type of object to be register for.
  4331. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4332. :return: None
  4333. """
  4334. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4335. new_reg_path = 'Software\\Classes\\'
  4336. # find if the current user is admin
  4337. try:
  4338. is_admin = os.getuid() == 0
  4339. except AttributeError:
  4340. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4341. if is_admin is True:
  4342. root_path = winreg.HKEY_LOCAL_MACHINE
  4343. else:
  4344. root_path = winreg.HKEY_CURRENT_USER
  4345. # create the keys
  4346. def set_reg(name, root_path, new_reg_path, value):
  4347. try:
  4348. winreg.CreateKey(root_path, new_reg_path)
  4349. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4350. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4351. return True
  4352. except WindowsError:
  4353. return False
  4354. # delete key in registry
  4355. def delete_reg(root_path, reg_path, key_to_del):
  4356. key_to_del_path = reg_path + key_to_del
  4357. try:
  4358. winreg.DeleteKey(root_path, key_to_del_path)
  4359. return True
  4360. except WindowsError:
  4361. return False
  4362. if obj_type is None or obj_type == 'excellon':
  4363. exc_list = \
  4364. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4365. exc_list = [x for x in exc_list if x != '']
  4366. # register all keys in the Preferences window
  4367. for ext in exc_list:
  4368. new_k = new_reg_path + '.%s' % ext
  4369. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4370. # and unregister those that are no longer in the Preferences windows but are in the file
  4371. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4372. if ext not in exc_list:
  4373. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4374. # now write the updated extensions to the self.defaults
  4375. # new_ext = ''
  4376. # for ext in exc_list:
  4377. # new_ext = new_ext + ext + ', '
  4378. # self.defaults["fa_excellon"] = new_ext
  4379. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4380. if obj_type is None or obj_type == 'gcode':
  4381. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4382. gco_list = [x for x in gco_list if x != '']
  4383. # register all keys in the Preferences window
  4384. for ext in gco_list:
  4385. new_k = new_reg_path + '.%s' % ext
  4386. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4387. # and unregister those that are no longer in the Preferences windows but are in the file
  4388. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4389. if ext not in gco_list:
  4390. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4391. # now write the updated extensions to the self.defaults
  4392. # new_ext = ''
  4393. # for ext in gco_list:
  4394. # new_ext = new_ext + ext + ', '
  4395. # self.defaults["fa_gcode"] = new_ext
  4396. self.inform.emit('[success] %s' %
  4397. _("Selected GCode file extensions registered with FlatCAM."))
  4398. if obj_type is None or obj_type == 'gerber':
  4399. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4400. grb_list = [x for x in grb_list if x != '']
  4401. # register all keys in the Preferences window
  4402. for ext in grb_list:
  4403. new_k = new_reg_path + '.%s' % ext
  4404. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4405. # and unregister those that are no longer in the Preferences windows but are in the file
  4406. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4407. if ext not in grb_list:
  4408. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4409. # now write the updated extensions to the self.defaults
  4410. # new_ext = ''
  4411. # for ext in grb_list:
  4412. # new_ext = new_ext + ext + ', '
  4413. # self.defaults["fa_gerber"] = new_ext
  4414. self.inform.emit('[success] %s' %
  4415. _("Selected Gerber file extensions registered with FlatCAM."))
  4416. def add_extension(self, ext_type):
  4417. """
  4418. Add a file extension to the list for a specific object
  4419. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4420. :return:
  4421. """
  4422. if ext_type == 'excellon':
  4423. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4424. if new_ext == '':
  4425. return
  4426. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4427. if new_ext in old_val:
  4428. return
  4429. old_val.append(new_ext)
  4430. old_val.sort()
  4431. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4432. if ext_type == 'gcode':
  4433. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4434. if new_ext == '':
  4435. return
  4436. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4437. if new_ext in old_val:
  4438. return
  4439. old_val.append(new_ext)
  4440. old_val.sort()
  4441. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4442. if ext_type == 'gerber':
  4443. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4444. if new_ext == '':
  4445. return
  4446. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4447. if new_ext in old_val:
  4448. return
  4449. old_val.append(new_ext)
  4450. old_val.sort()
  4451. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4452. if ext_type == 'keyword':
  4453. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4454. if new_kw == '':
  4455. return
  4456. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4457. if new_kw in old_val:
  4458. return
  4459. old_val.append(new_kw)
  4460. old_val.sort()
  4461. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4462. # update the self.myKeywords so the model is updated
  4463. self.autocomplete_kw_list = \
  4464. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4465. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4466. self.shell._edit.set_model_data(self.myKeywords)
  4467. def del_extension(self, ext_type):
  4468. """
  4469. Remove a file extension from the list for a specific object
  4470. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4471. :return:
  4472. """
  4473. if ext_type == 'excellon':
  4474. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4475. if new_ext == '':
  4476. return
  4477. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4478. if new_ext not in old_val:
  4479. return
  4480. old_val.remove(new_ext)
  4481. old_val.sort()
  4482. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4483. if ext_type == 'gcode':
  4484. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4485. if new_ext == '':
  4486. return
  4487. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4488. if new_ext not in old_val:
  4489. return
  4490. old_val.remove(new_ext)
  4491. old_val.sort()
  4492. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4493. if ext_type == 'gerber':
  4494. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4495. if new_ext == '':
  4496. return
  4497. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4498. if new_ext not in old_val:
  4499. return
  4500. old_val.remove(new_ext)
  4501. old_val.sort()
  4502. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4503. if ext_type == 'keyword':
  4504. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4505. if new_kw == '':
  4506. return
  4507. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4508. if new_kw not in old_val:
  4509. return
  4510. old_val.remove(new_kw)
  4511. old_val.sort()
  4512. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4513. # update the self.myKeywords so the model is updated
  4514. self.autocomplete_kw_list = \
  4515. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4516. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4517. self.shell._edit.set_model_data(self.myKeywords)
  4518. def restore_extensions(self, ext_type):
  4519. """
  4520. Restore all file extensions associations with FlatCAM, for a specific object
  4521. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4522. :return:
  4523. """
  4524. if ext_type == 'excellon':
  4525. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4526. # for the ability to open Excellon files with .txt extension
  4527. new_exc_list = deepcopy(self.exc_list)
  4528. try:
  4529. new_exc_list.remove('txt')
  4530. except ValueError:
  4531. pass
  4532. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4533. if ext_type == 'gcode':
  4534. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4535. if ext_type == 'gerber':
  4536. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4537. if ext_type == 'keyword':
  4538. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4539. # update the self.myKeywords so the model is updated
  4540. self.autocomplete_kw_list = self.default_keywords
  4541. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4542. self.shell._edit.set_model_data(self.myKeywords)
  4543. def delete_all_extensions(self, ext_type):
  4544. """
  4545. Delete all file extensions associations with FlatCAM, for a specific object
  4546. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4547. :return:
  4548. """
  4549. if ext_type == 'excellon':
  4550. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4551. if ext_type == 'gcode':
  4552. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4553. if ext_type == 'gerber':
  4554. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4555. if ext_type == 'keyword':
  4556. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4557. # update the self.myKeywords so the model is updated
  4558. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4559. self.shell._edit.set_model_data(self.myKeywords)
  4560. def on_edit_join(self, name=None):
  4561. """
  4562. Callback for Edit->Join. Joins the selected geometry objects into
  4563. a new one.
  4564. :return: None
  4565. """
  4566. self.report_usage("on_edit_join()")
  4567. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4568. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4569. geo_type_set = set()
  4570. objs = self.collection.get_selected()
  4571. if len(objs) < 2:
  4572. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4573. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4574. return 'fail'
  4575. for obj in objs:
  4576. geo_type_set.add(obj.multigeo)
  4577. # if len(geo_type_list) == 1 means that all list elements are the same
  4578. if len(geo_type_set) != 1:
  4579. self.inform.emit('[ERROR] %s' %
  4580. _("Failed join. The Geometry objects are of different types.\n"
  4581. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4582. "convert from one to another and retry joining \n"
  4583. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4584. "the result may not be what was expected. \n"
  4585. "Check the generated GCODE."))
  4586. return
  4587. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4588. if True in geo_type_set:
  4589. def initialize(geo_obj, app):
  4590. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  4591. app.inform.emit('[success] %s.' % _("Multigeo. Geometry merging finished"))
  4592. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4593. for v in obj.tools.values():
  4594. v['data']['name'] = obj_name_multi
  4595. self.new_object("geometry", obj_name_multi, initialize)
  4596. else:
  4597. def initialize(geo_obj, app):
  4598. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  4599. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4600. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4601. for v in obj.tools.values():
  4602. v['data']['name'] = obj_name_single
  4603. self.new_object("geometry", obj_name_single, initialize)
  4604. self.should_we_save = True
  4605. def on_edit_join_exc(self):
  4606. """
  4607. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4608. a new Excellon.
  4609. :return: None
  4610. """
  4611. self.report_usage("on_edit_join_exc()")
  4612. objs = self.collection.get_selected()
  4613. for obj in objs:
  4614. if not isinstance(obj, FlatCAMExcellon):
  4615. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  4616. return
  4617. if len(objs) < 2:
  4618. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4619. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4620. return 'fail'
  4621. def initialize(exc_obj, app):
  4622. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=exc_obj)
  4623. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  4624. self.new_object("excellon", 'Combo_Excellon', initialize)
  4625. self.should_we_save = True
  4626. def on_edit_join_grb(self):
  4627. """
  4628. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4629. a new Gerber object.
  4630. :return: None
  4631. """
  4632. self.report_usage("on_edit_join_grb()")
  4633. objs = self.collection.get_selected()
  4634. for obj in objs:
  4635. if not isinstance(obj, FlatCAMGerber):
  4636. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  4637. return
  4638. if len(objs) < 2:
  4639. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4640. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4641. return 'fail'
  4642. def initialize(grb_obj, app):
  4643. FlatCAMGerber.merge(self, grb_list=objs, grb_final=grb_obj)
  4644. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  4645. self.new_object("gerber", 'Combo_Gerber', initialize)
  4646. self.should_we_save = True
  4647. def on_convert_singlegeo_to_multigeo(self):
  4648. """
  4649. Called for converting a Geometry object from single-geo to multi-geo.
  4650. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4651. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4652. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4653. the solid-geometry of that tool.
  4654. :return: None
  4655. """
  4656. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4657. obj = self.collection.get_active()
  4658. if obj is None:
  4659. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  4660. return
  4661. if not isinstance(obj, FlatCAMGeometry):
  4662. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4663. return
  4664. obj.multigeo = True
  4665. for tooluid, dict_value in obj.tools.items():
  4666. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4667. if not isinstance(obj.solid_geometry, list):
  4668. obj.solid_geometry = [obj.solid_geometry]
  4669. obj.solid_geometry[:] = []
  4670. obj.plot()
  4671. self.should_we_save = True
  4672. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  4673. def on_convert_multigeo_to_singlegeo(self):
  4674. """
  4675. Called for converting a Geometry object from multi-geo to single-geo.
  4676. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4677. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4678. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4679. the solid-geometry of that tool.
  4680. :return: None
  4681. """
  4682. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4683. obj = self.collection.get_active()
  4684. if obj is None:
  4685. self.inform.emit('[ERROR_NOTCL] %s' %
  4686. _("Failed. Select a Geometry Object and try again."))
  4687. return
  4688. if not isinstance(obj, FlatCAMGeometry):
  4689. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4690. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4691. return
  4692. obj.multigeo = False
  4693. total_solid_geometry = []
  4694. for tooluid, dict_value in obj.tools.items():
  4695. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4696. # clear the original geometry
  4697. dict_value['solid_geometry'][:] = []
  4698. obj.solid_geometry = deepcopy(total_solid_geometry)
  4699. obj.plot()
  4700. self.should_we_save = True
  4701. self.inform.emit('[success] %s' %
  4702. _("A Geometry object was converted to SingleGeo type."))
  4703. def on_defaults_dict_change(self, field):
  4704. """
  4705. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4706. Edit -> Preferences tab window.
  4707. :param field: the key of the self.defaults dictionary that was changed.
  4708. :return: None
  4709. """
  4710. self.defaults_write_form_field(field)
  4711. if field == "units":
  4712. self.set_screen_units(self.defaults['units'])
  4713. def set_screen_units(self, units):
  4714. """
  4715. Set the FlatCAM units on the status bar.
  4716. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4717. :return: None
  4718. """
  4719. self.ui.units_label.setText("[" + units.lower() + "]")
  4720. def on_toggle_units_click(self):
  4721. try:
  4722. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4723. except (TypeError, AttributeError):
  4724. pass
  4725. if self.defaults["units"] == 'MM':
  4726. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4727. else:
  4728. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4729. self.on_toggle_units(no_pref=True)
  4730. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4731. lambda: self.on_toggle_units(no_pref=False))
  4732. def on_toggle_units(self, no_pref=False):
  4733. """
  4734. Callback for the Units radio-button change in the Preferences tab.
  4735. Changes the application's default units adn for the project too.
  4736. If changing the project's units, the change propagates to all of
  4737. the objects in the project.
  4738. :return: None
  4739. """
  4740. self.report_usage("on_toggle_units")
  4741. if self.toggle_units_ignore:
  4742. return
  4743. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4744. # If option is the same, then ignore
  4745. if new_units == self.defaults["units"].upper():
  4746. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4747. return
  4748. # Options to scale
  4749. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4750. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4751. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4752. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4753. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4754. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4755. "excellon_editor_slot_lin_pitch",
  4756. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4757. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4758. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4759. "geometry_feedrate_probe", "geometry_startz",
  4760. 'cncjob_tooldia',
  4761. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4762. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4763. "tools_nccnewdia",
  4764. "tools_2sided_drilldia", "tools_film_boundary",
  4765. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4766. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4767. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4768. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4769. "tools_transform_offset_y",
  4770. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4771. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4772. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4773. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4774. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4775. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4776. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  4777. "tools_fiducials_mode", "tools_fiducials_second_pos", "tools_fiducials_type",
  4778. "tools_fiducials_line_thickness",
  4779. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  4780. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  4781. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  4782. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  4783. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  4784. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance"]
  4785. def scale_defaults(sfactor):
  4786. for dim in dimensions:
  4787. if dim == 'excellon_toolchangexy':
  4788. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4789. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4790. coords_xy[0] *= sfactor
  4791. coords_xy[1] *= sfactor
  4792. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4793. self.decimals, coords_xy[1])
  4794. elif dim == 'geometry_toolchangexy':
  4795. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4796. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4797. coords_xy[0] *= sfactor
  4798. coords_xy[1] *= sfactor
  4799. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4800. self.decimals, coords_xy[1])
  4801. elif dim == 'geometry_cnctooldia':
  4802. tools_diameters = []
  4803. try:
  4804. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4805. tools_diameters = [eval(a) for a in tools_string if a != '']
  4806. except Exception as e:
  4807. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4808. self.defaults['geometry_cnctooldia'] = ''
  4809. for t in range(len(tools_diameters)):
  4810. tools_diameters[t] *= sfactor
  4811. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  4812. elif dim == 'tools_ncctools':
  4813. ncctools = []
  4814. try:
  4815. tools_string = self.defaults["tools_ncctools"].split(",")
  4816. ncctools = [eval(a) for a in tools_string if a != '']
  4817. except Exception as e:
  4818. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4819. self.defaults['tools_ncctools'] = ''
  4820. for t in range(len(ncctools)):
  4821. ncctools[t] *= sfactor
  4822. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  4823. elif dim == 'tools_solderpaste_tools':
  4824. sptools = []
  4825. try:
  4826. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4827. sptools = [eval(a) for a in tools_string if a != '']
  4828. except Exception as e:
  4829. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4830. self.defaults['tools_solderpaste_tools'] = ""
  4831. for t in range(len(sptools)):
  4832. sptools[t] *= sfactor
  4833. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  4834. elif dim == 'tools_solderpaste_xy_toolchange':
  4835. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4836. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4837. sp_coords[0] *= sfactor
  4838. sp_coords[1] *= sfactor
  4839. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  4840. self.decimals, sp_coords[1])
  4841. elif dim == 'global_gridx' or dim == 'global_gridy':
  4842. if new_units == 'IN':
  4843. val = 0.1
  4844. try:
  4845. val = float(self.defaults[dim]) * sfactor
  4846. except Exception as e:
  4847. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4848. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  4849. else:
  4850. val = 0.1
  4851. try:
  4852. val = float(self.defaults[dim]) * sfactor
  4853. except Exception as e:
  4854. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4855. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  4856. else:
  4857. val = 0.1
  4858. if self.defaults[dim]:
  4859. try:
  4860. val = float(self.defaults[dim]) * sfactor
  4861. except Exception as e:
  4862. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4863. self.defaults[dim] = val
  4864. # The scaling factor depending on choice of units.
  4865. factor = 25.4 if new_units == 'MM' else 1/25.4
  4866. # Changing project units. Warn user.
  4867. msgbox = QtWidgets.QMessageBox()
  4868. msgbox.setWindowTitle(_("Toggle Units"))
  4869. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4870. msgbox.setText(_("Changing the units of the project\n"
  4871. "will scale all objects.\n\n"
  4872. "Do you want to continue?"))
  4873. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4874. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4875. msgbox.setDefaultButton(bt_ok)
  4876. msgbox.exec_()
  4877. response = msgbox.clickedButton()
  4878. if response == bt_ok:
  4879. if no_pref is False:
  4880. self.defaults_read_form()
  4881. scale_defaults(factor)
  4882. self.defaults_write_form(fl_units=new_units)
  4883. self.defaults["units"] = new_units
  4884. # update the defaults from form, some may assume that the conversion is enough and it's not
  4885. self.on_options_app2project()
  4886. # update the objects
  4887. for obj in self.collection.get_list():
  4888. obj.convert_units(new_units)
  4889. # make that the properties stored in the object are also updated
  4890. self.object_changed.emit(obj)
  4891. # rebuild the object UI
  4892. obj.build_ui()
  4893. # change this only if the workspace is active
  4894. if self.defaults['global_workspace'] is True:
  4895. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  4896. # adjust the grid values on the main toolbar
  4897. val_x = float(self.defaults['global_gridx']) * factor
  4898. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  4899. current = self.collection.get_active()
  4900. if current is not None:
  4901. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4902. if not isinstance(current, FlatCAMGeometry):
  4903. current.to_form()
  4904. # replot all objects
  4905. self.plot_all()
  4906. # set the status labels to reflect the current FlatCAM units
  4907. self.set_screen_units(new_units)
  4908. # signal to the app that we changed the object properties and it shoud save the project
  4909. self.should_we_save = True
  4910. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  4911. else:
  4912. # Undo toggling
  4913. self.toggle_units_ignore = True
  4914. if self.defaults['units'].upper() == 'MM':
  4915. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4916. else:
  4917. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4918. self.toggle_units_ignore = False
  4919. # store the grid values so they are not changed in the next step
  4920. val_x = float(self.defaults['global_gridx'])
  4921. val_y = float(self.defaults['global_gridy'])
  4922. self.inform.emit('[WARNING_NOTCL]%s' % _("Units conversion cancelled."))
  4923. self.defaults_read_form()
  4924. # the self.defaults_read_form() will update all defaults values in self.defaults from the GUI elements but
  4925. # I don't want it for the grid values, so I update them here
  4926. self.defaults['global_gridx'] = val_x
  4927. self.defaults['global_gridy'] = val_y
  4928. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  4929. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  4930. def on_fullscreen(self, disable=False):
  4931. self.report_usage("on_fullscreen()")
  4932. if self.toggle_fscreen is False and disable is False:
  4933. # self.ui.showFullScreen()
  4934. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4935. a = self.ui.geometry()
  4936. self.x_pos = a.x()
  4937. self.y_pos = a.y()
  4938. self.width = a.width()
  4939. self.height = a.height()
  4940. # set new geometry to full desktop rect
  4941. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4942. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4943. # everything else will not work without this hack. This happen in Windows.
  4944. # https://bugreports.qt.io/browse/QTBUG-41309
  4945. desktop = QtWidgets.QApplication.desktop()
  4946. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4947. rec = desktop.screenGeometry(screen)
  4948. x = rec.x() - 1
  4949. y = rec.y() - 1
  4950. h = rec.height() + 2
  4951. w = rec.width() + 2
  4952. self.ui.setGeometry(x, y, w, h)
  4953. self.ui.show()
  4954. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4955. tb.setVisible(False)
  4956. self.ui.splitter_left.setVisible(False)
  4957. self.toggle_fscreen = True
  4958. elif self.toggle_fscreen is True or disable is True:
  4959. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  4960. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4961. self.ui.showNormal()
  4962. self.restore_toolbar_view()
  4963. self.ui.splitter_left.setVisible(True)
  4964. self.toggle_fscreen = False
  4965. def on_toggle_plotarea(self):
  4966. self.report_usage("on_toggle_plotarea()")
  4967. try:
  4968. name = self.ui.plot_tab_area.widget(0).objectName()
  4969. except AttributeError:
  4970. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4971. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4972. self.ui.plot_tab_area.protectTab(0)
  4973. return
  4974. if name != 'plotarea':
  4975. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4976. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4977. self.ui.plot_tab_area.protectTab(0)
  4978. else:
  4979. self.ui.plot_tab_area.closeTab(0)
  4980. def on_toggle_notebook(self):
  4981. if self.ui.splitter.sizes()[0] == 0:
  4982. self.ui.splitter.setSizes([1, 1])
  4983. self.ui.menu_toggle_nb.setChecked(True)
  4984. else:
  4985. self.ui.splitter.setSizes([0, 1])
  4986. self.ui.menu_toggle_nb.setChecked(False)
  4987. def on_toggle_axis(self):
  4988. self.report_usage("on_toggle_axis()")
  4989. if self.toggle_axis is False:
  4990. if self.is_legacy is False:
  4991. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4992. parent=self.plotcanvas.view.scene)
  4993. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  4994. parent=self.plotcanvas.view.scene)
  4995. else:
  4996. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  4997. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  4998. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  4999. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  5000. self.plotcanvas.canvas.draw()
  5001. self.toggle_axis = True
  5002. else:
  5003. if self.is_legacy is False:
  5004. self.plotcanvas.v_line.parent = None
  5005. self.plotcanvas.h_line.parent = None
  5006. else:
  5007. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  5008. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  5009. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  5010. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  5011. self.plotcanvas.canvas.draw()
  5012. self.toggle_axis = False
  5013. def on_toggle_grid(self):
  5014. self.report_usage("on_toggle_grid()")
  5015. self.ui.grid_snap_btn.trigger()
  5016. def on_toggle_grid_lines(self):
  5017. self.report_usage("on_toggle_grd_lines()")
  5018. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  5019. if tt_settings.contains("theme"):
  5020. theme = tt_settings.value('theme', type=str)
  5021. else:
  5022. theme = 'white'
  5023. if self.toggle_grid_lines is False:
  5024. if self.is_legacy is False:
  5025. if theme == 'white':
  5026. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  5027. else:
  5028. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  5029. else:
  5030. self.plotcanvas.axes.grid(True)
  5031. try:
  5032. self.plotcanvas.canvas.draw()
  5033. except IndexError:
  5034. pass
  5035. pass
  5036. self.toggle_grid_lines = True
  5037. else:
  5038. if self.is_legacy is False:
  5039. if theme == 'white':
  5040. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  5041. else:
  5042. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  5043. else:
  5044. self.plotcanvas.axes.grid(False)
  5045. try:
  5046. self.plotcanvas.canvas.draw()
  5047. except IndexError:
  5048. pass
  5049. self.toggle_grid_lines = False
  5050. if self.is_legacy is False:
  5051. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  5052. # - perhaps is a bug in VisPy implementation
  5053. if self.grid_status() is True:
  5054. self.app_cursor.enabled = False
  5055. self.app_cursor.enabled = True
  5056. else:
  5057. self.app_cursor.enabled = True
  5058. self.app_cursor.enabled = False
  5059. def show_preferences_gui(self):
  5060. """
  5061. Called to initialize and show the Preferences GUI
  5062. :return: None
  5063. """
  5064. self.gen_form = self.ui.general_defaults_form
  5065. self.ger_form = self.ui.gerber_defaults_form
  5066. self.exc_form = self.ui.excellon_defaults_form
  5067. self.geo_form = self.ui.geometry_defaults_form
  5068. self.cnc_form = self.ui.cncjob_defaults_form
  5069. self.tools_form = self.ui.tools_defaults_form
  5070. self.tools2_form = self.ui.tools2_defaults_form
  5071. self.fa_form = self.ui.util_defaults_form
  5072. try:
  5073. self.ui.general_scroll_area.takeWidget()
  5074. except Exception:
  5075. self.log.debug("Nothing to remove")
  5076. self.ui.general_scroll_area.setWidget(self.gen_form)
  5077. self.gen_form.show()
  5078. try:
  5079. self.ui.gerber_scroll_area.takeWidget()
  5080. except Exception:
  5081. self.log.debug("Nothing to remove")
  5082. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  5083. self.ger_form.show()
  5084. try:
  5085. self.ui.excellon_scroll_area.takeWidget()
  5086. except Exception:
  5087. self.log.debug("Nothing to remove")
  5088. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  5089. self.exc_form.show()
  5090. try:
  5091. self.ui.geometry_scroll_area.takeWidget()
  5092. except Exception:
  5093. self.log.debug("Nothing to remove")
  5094. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  5095. self.geo_form.show()
  5096. try:
  5097. self.ui.cncjob_scroll_area.takeWidget()
  5098. except Exception:
  5099. self.log.debug("Nothing to remove")
  5100. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  5101. self.cnc_form.show()
  5102. try:
  5103. self.ui.tools_scroll_area.takeWidget()
  5104. except Exception:
  5105. self.log.debug("Nothing to remove")
  5106. self.ui.tools_scroll_area.setWidget(self.tools_form)
  5107. self.tools_form.show()
  5108. try:
  5109. self.ui.tools2_scroll_area.takeWidget()
  5110. except Exception:
  5111. self.log.debug("Nothing to remove")
  5112. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  5113. self.tools2_form.show()
  5114. try:
  5115. self.ui.fa_scroll_area.takeWidget()
  5116. except Exception:
  5117. self.log.debug("Nothing to remove")
  5118. self.ui.fa_scroll_area.setWidget(self.fa_form)
  5119. self.fa_form.show()
  5120. self.log.debug("Finished Preferences GUI form initialization.")
  5121. # self.options2form()
  5122. def init_color_pickers_in_preferences_gui(self):
  5123. # Init Plot Colors
  5124. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  5125. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5126. "background-color:%s;"
  5127. "border-color: dimgray" % str(self.defaults['global_plot_fill'])[:7])
  5128. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  5129. int(self.defaults['global_plot_fill'][7:9], 16))
  5130. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  5131. int(self.defaults['global_plot_fill'][7:9], 16))
  5132. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  5133. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5134. "background-color:%s;"
  5135. "border-color: dimgray" % str(self.defaults['global_plot_line'])[:7])
  5136. # Init Left-Right Selection colors
  5137. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  5138. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5139. "background-color:%s;"
  5140. "border-color: dimgray" % str(self.defaults['global_sel_fill'])[:7])
  5141. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  5142. int(self.defaults['global_sel_fill'][7:9], 16))
  5143. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  5144. int(self.defaults['global_sel_fill'][7:9], 16))
  5145. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  5146. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5147. "background-color:%s;"
  5148. "border-color: dimgray" % str(self.defaults['global_sel_line'])[:7])
  5149. # Init Right-Left Selection colors
  5150. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  5151. self.defaults['global_alt_sel_fill'])
  5152. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5153. "background-color:%s;"
  5154. "border-color: dimgray" % str(self.defaults['global_alt_sel_fill'])[:7])
  5155. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  5156. int(self.defaults['global_sel_fill'][7:9], 16))
  5157. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  5158. int(self.defaults['global_sel_fill'][7:9], 16))
  5159. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  5160. self.defaults['global_alt_sel_line'])
  5161. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5162. "background-color:%s;"
  5163. "border-color: dimgray" % str(self.defaults['global_alt_sel_line'])[:7])
  5164. # Init Draw color and Selection Draw Color
  5165. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  5166. self.defaults['global_draw_color'])
  5167. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5168. "background-color:%s;"
  5169. "border-color: dimgray" % str(self.defaults['global_draw_color'])[:7])
  5170. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  5171. self.defaults['global_sel_draw_color'])
  5172. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5173. "background-color:%s;"
  5174. "border-color: dimgray" % str(self.defaults['global_sel_draw_color'])[:7])
  5175. # Init Project Items color
  5176. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  5177. self.defaults['global_proj_item_color'])
  5178. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5179. "background-color:%s;"
  5180. "border-color: dimgray" % str(self.defaults['global_proj_item_color'])[:7])
  5181. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  5182. self.defaults['global_proj_item_dis_color'])
  5183. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5184. "background-color:%s;"
  5185. "border-color: dimgray" % str(self.defaults['global_proj_item_dis_color'])[:7])
  5186. # Init the Annotation CNC Job color
  5187. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  5188. self.defaults['cncjob_annotation_fontcolor'])
  5189. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5190. "background-color:%s;"
  5191. "border-color: dimgray" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  5192. # Init the Tool Film color
  5193. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  5194. self.defaults['tools_film_color'])
  5195. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5196. "background-color:%s;"
  5197. "border-color: dimgray" % str(self.defaults['tools_film_color'])[:7]
  5198. )
  5199. # Init the Tool QRCode colors
  5200. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  5201. self.defaults['tools_qrcode_fill_color'])
  5202. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5203. "background-color:%s;"
  5204. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  5205. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  5206. self.defaults['tools_qrcode_back_color'])
  5207. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5208. "background-color:%s;"
  5209. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])[:7])
  5210. def on_excellon_defaults_button(self):
  5211. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  5212. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  5213. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  5214. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  5215. self.defaults_form_fields["excellon_zeros"].set_value('L')
  5216. self.defaults_form_fields["excellon_units"].set_value('INCH')
  5217. log.debug("Excellon app defaults loaded ...")
  5218. def on_update_exc_export(self, state):
  5219. """
  5220. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5221. if the update_excellon_cb checkbox is checked
  5222. :param state: state of the checkbox whose signals is tied to his slot
  5223. :return:
  5224. """
  5225. if state:
  5226. # first try to disconnect
  5227. try:
  5228. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.\
  5229. disconnect(self.on_excellon_format_changed)
  5230. except TypeError:
  5231. pass
  5232. try:
  5233. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.\
  5234. disconnect(self.on_excellon_format_changed)
  5235. except TypeError:
  5236. pass
  5237. try:
  5238. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.\
  5239. disconnect(self.on_excellon_format_changed)
  5240. except TypeError:
  5241. pass
  5242. try:
  5243. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.\
  5244. disconnect(self.on_excellon_format_changed)
  5245. except TypeError:
  5246. pass
  5247. try:
  5248. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5249. disconnect(self.on_excellon_zeros_changed)
  5250. except TypeError:
  5251. pass
  5252. try:
  5253. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5254. disconnect(self.on_excellon_zeros_changed)
  5255. except TypeError:
  5256. pass
  5257. # the connect them
  5258. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  5259. self.on_excellon_format_changed)
  5260. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  5261. self.on_excellon_format_changed)
  5262. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  5263. self.on_excellon_format_changed)
  5264. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  5265. self.on_excellon_format_changed)
  5266. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5267. self.on_excellon_zeros_changed)
  5268. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5269. self.on_excellon_units_changed)
  5270. else:
  5271. # disconnect the signals
  5272. try:
  5273. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  5274. disconnect(self.on_excellon_format_changed)
  5275. except TypeError:
  5276. pass
  5277. try:
  5278. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  5279. disconnect(self.on_excellon_format_changed)
  5280. except TypeError:
  5281. pass
  5282. try:
  5283. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  5284. disconnect(self.on_excellon_format_changed)
  5285. except TypeError:
  5286. pass
  5287. try:
  5288. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  5289. disconnect(self.on_excellon_format_changed)
  5290. except TypeError:
  5291. pass
  5292. try:
  5293. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5294. disconnect(self.on_excellon_zeros_changed)
  5295. except TypeError:
  5296. pass
  5297. try:
  5298. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5299. disconnect(self.on_excellon_zeros_changed)
  5300. except TypeError:
  5301. pass
  5302. def on_excellon_format_changed(self):
  5303. """
  5304. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5305. :return: None
  5306. """
  5307. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5308. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5309. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5310. )
  5311. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5312. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5313. )
  5314. else:
  5315. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5316. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5317. )
  5318. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5319. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5320. )
  5321. def on_excellon_zeros_changed(self):
  5322. """
  5323. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5324. :return: None
  5325. """
  5326. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5327. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5328. )
  5329. def on_excellon_units_changed(self):
  5330. """
  5331. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5332. :return: None
  5333. """
  5334. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5335. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5336. )
  5337. self.on_excellon_format_changed()
  5338. # Setting plot colors handlers
  5339. def on_pf_color_entry(self):
  5340. self.defaults['global_plot_fill'] = \
  5341. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5342. self.defaults['global_plot_fill'][7:9]
  5343. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5344. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5345. def on_pf_color_button(self):
  5346. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5347. c_dialog = QtWidgets.QColorDialog()
  5348. plot_fill_color = c_dialog.getColor(initial=current_color)
  5349. if plot_fill_color.isValid() is False:
  5350. return
  5351. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5352. "background-color:%s" % str(plot_fill_color.name()))
  5353. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5354. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5355. self.defaults['global_plot_fill'] = new_val
  5356. def on_pf_color_spinner(self):
  5357. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5358. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5359. self.defaults['global_plot_fill'] = \
  5360. self.defaults['global_plot_fill'][:7] + \
  5361. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5362. self.defaults['global_plot_line'] = \
  5363. self.defaults['global_plot_line'][:7] + \
  5364. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5365. def on_pf_color_slider(self):
  5366. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5367. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5368. def on_pl_color_entry(self):
  5369. self.defaults['global_plot_line'] = \
  5370. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5371. self.defaults['global_plot_line'][7:9]
  5372. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5373. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5374. def on_pl_color_button(self):
  5375. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5376. # print(current_color)
  5377. c_dialog = QtWidgets.QColorDialog()
  5378. plot_line_color = c_dialog.getColor(initial=current_color)
  5379. if plot_line_color.isValid() is False:
  5380. return
  5381. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5382. "background-color:%s" % str(plot_line_color.name()))
  5383. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5384. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5385. self.defaults['global_plot_line'] = new_val_line
  5386. # Setting selection colors (left - right) handlers
  5387. def on_sf_color_entry(self):
  5388. self.defaults['global_sel_fill'] = \
  5389. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5390. self.defaults['global_sel_fill'][7:9]
  5391. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5392. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5393. def on_sf_color_button(self):
  5394. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5395. c_dialog = QtWidgets.QColorDialog()
  5396. plot_fill_color = c_dialog.getColor(initial=current_color)
  5397. if plot_fill_color.isValid() is False:
  5398. return
  5399. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5400. "background-color:%s" % str(plot_fill_color.name()))
  5401. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5402. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5403. self.defaults['global_sel_fill'] = new_val
  5404. def on_sf_color_spinner(self):
  5405. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5406. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5407. self.defaults['global_sel_fill'] = \
  5408. self.defaults['global_sel_fill'][:7] + \
  5409. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5410. self.defaults['global_sel_line'] = \
  5411. self.defaults['global_sel_line'][:7] + \
  5412. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5413. def on_sf_color_slider(self):
  5414. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5415. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5416. def on_sl_color_entry(self):
  5417. self.defaults['global_sel_line'] = \
  5418. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5419. self.defaults['global_sel_line'][7:9]
  5420. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5421. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5422. def on_sl_color_button(self):
  5423. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5424. c_dialog = QtWidgets.QColorDialog()
  5425. plot_line_color = c_dialog.getColor(initial=current_color)
  5426. if plot_line_color.isValid() is False:
  5427. return
  5428. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5429. "background-color:%s" % str(plot_line_color.name()))
  5430. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5431. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5432. self.defaults['global_sel_line'] = new_val_line
  5433. # Setting selection colors (right - left) handlers
  5434. def on_alt_sf_color_entry(self):
  5435. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5436. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5437. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5438. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5439. def on_alt_sf_color_button(self):
  5440. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5441. c_dialog = QtWidgets.QColorDialog()
  5442. plot_fill_color = c_dialog.getColor(initial=current_color)
  5443. if plot_fill_color.isValid() is False:
  5444. return
  5445. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5446. "background-color:%s" % str(plot_fill_color.name()))
  5447. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5448. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5449. self.defaults['global_alt_sel_fill'] = new_val
  5450. def on_alt_sf_color_spinner(self):
  5451. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5452. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5453. self.defaults['global_alt_sel_fill'] = \
  5454. self.defaults['global_alt_sel_fill'][:7] + \
  5455. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5456. self.defaults['global_alt_sel_line'] = \
  5457. self.defaults['global_alt_sel_line'][:7] + \
  5458. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5459. def on_alt_sf_color_slider(self):
  5460. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5461. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5462. def on_alt_sl_color_entry(self):
  5463. self.defaults['global_alt_sel_line'] = \
  5464. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5465. self.defaults['global_alt_sel_line'][7:9]
  5466. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5467. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5468. def on_alt_sl_color_button(self):
  5469. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5470. c_dialog = QtWidgets.QColorDialog()
  5471. plot_line_color = c_dialog.getColor(initial=current_color)
  5472. if plot_line_color.isValid() is False:
  5473. return
  5474. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5475. "background-color:%s" % str(plot_line_color.name()))
  5476. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5477. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5478. self.defaults['global_alt_sel_line'] = new_val_line
  5479. # Setting Editor colors
  5480. def on_draw_color_entry(self):
  5481. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5482. .draw_color_entry.get_value()
  5483. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5484. "background-color:%s" % str(self.defaults['global_draw_color']))
  5485. def on_draw_color_button(self):
  5486. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5487. c_dialog = QtWidgets.QColorDialog()
  5488. draw_color = c_dialog.getColor(initial=current_color)
  5489. if draw_color.isValid() is False:
  5490. return
  5491. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5492. "background-color:%s" % str(draw_color.name()))
  5493. new_val = str(draw_color.name())
  5494. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5495. self.defaults['global_draw_color'] = new_val
  5496. def on_sel_draw_color_entry(self):
  5497. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5498. .sel_draw_color_entry.get_value()
  5499. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5500. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5501. def on_sel_draw_color_button(self):
  5502. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5503. c_dialog = QtWidgets.QColorDialog()
  5504. sel_draw_color = c_dialog.getColor(initial=current_color)
  5505. if sel_draw_color.isValid() is False:
  5506. return
  5507. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5508. "background-color:%s" % str(sel_draw_color.name()))
  5509. new_val_sel = str(sel_draw_color.name())
  5510. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5511. self.defaults['global_sel_draw_color'] = new_val_sel
  5512. def on_proj_color_entry(self):
  5513. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5514. .proj_color_entry.get_value()
  5515. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5516. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5517. def on_proj_color_button(self):
  5518. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5519. c_dialog = QtWidgets.QColorDialog()
  5520. proj_color = c_dialog.getColor(initial=current_color)
  5521. if proj_color.isValid() is False:
  5522. return
  5523. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5524. "background-color:%s" % str(proj_color.name()))
  5525. new_val_sel = str(proj_color.name())
  5526. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5527. self.defaults['global_proj_item_color'] = new_val_sel
  5528. def on_proj_color_dis_entry(self):
  5529. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5530. .proj_color_dis_entry.get_value()
  5531. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5532. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5533. def on_proj_color_dis_button(self):
  5534. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5535. c_dialog = QtWidgets.QColorDialog()
  5536. proj_color = c_dialog.getColor(initial=current_color)
  5537. if proj_color.isValid() is False:
  5538. return
  5539. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5540. "background-color:%s" % str(proj_color.name()))
  5541. new_val_sel = str(proj_color.name())
  5542. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5543. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5544. def on_annotation_fontcolor_entry(self):
  5545. self.defaults['cncjob_annotation_fontcolor'] = \
  5546. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5547. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5548. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5549. def on_annotation_fontcolor_button(self):
  5550. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5551. c_dialog = QtWidgets.QColorDialog()
  5552. annotation_color = c_dialog.getColor(initial=current_color)
  5553. if annotation_color.isValid() is False:
  5554. return
  5555. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5556. "background-color:%s" % str(annotation_color.name()))
  5557. new_val_sel = str(annotation_color.name())
  5558. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5559. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5560. def on_film_color_entry(self):
  5561. self.defaults['tools_film_color'] = \
  5562. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5563. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5564. "background-color:%s;"
  5565. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  5566. )
  5567. def on_film_color_button(self):
  5568. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5569. c_dialog = QtWidgets.QColorDialog()
  5570. film_color = c_dialog.getColor(initial=current_color)
  5571. if film_color.isValid() is False:
  5572. return
  5573. # if new color is different then mark that the Preferences are changed
  5574. if film_color != current_color:
  5575. self.on_preferences_edited()
  5576. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5577. "background-color:%s;"
  5578. "border-color: dimgray" % str(film_color.name())
  5579. )
  5580. new_val_sel = str(film_color.name())
  5581. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5582. self.defaults['tools_film_color'] = new_val_sel
  5583. def on_qrcode_fill_color_entry(self):
  5584. self.defaults['tools_qrcode_fill_color'] = \
  5585. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  5586. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5587. "background-color:%s;"
  5588. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  5589. )
  5590. def on_qrcode_fill_color_button(self):
  5591. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  5592. c_dialog = QtWidgets.QColorDialog()
  5593. fill_color = c_dialog.getColor(initial=current_color)
  5594. if fill_color.isValid() is False:
  5595. return
  5596. # if new color is different then mark that the Preferences are changed
  5597. if fill_color != current_color:
  5598. self.on_preferences_edited()
  5599. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5600. "background-color:%s;"
  5601. "border-color: dimgray" % str(fill_color.name())
  5602. )
  5603. new_val_sel = str(fill_color.name())
  5604. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  5605. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  5606. def on_qrcode_back_color_entry(self):
  5607. self.defaults['tools_qrcode_back_color'] = \
  5608. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  5609. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5610. "background-color:%s;"
  5611. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  5612. )
  5613. def on_qrcode_back_color_button(self):
  5614. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  5615. c_dialog = QtWidgets.QColorDialog()
  5616. back_color = c_dialog.getColor(initial=current_color)
  5617. if back_color.isValid() is False:
  5618. return
  5619. # if new color is different then mark that the Preferences are changed
  5620. if back_color != current_color:
  5621. self.on_preferences_edited()
  5622. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5623. "background-color:%s;"
  5624. "border-color: dimgray" % str(back_color.name())
  5625. )
  5626. new_val_sel = str(back_color.name())
  5627. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  5628. self.defaults['tools_qrcode_back_color'] = new_val_sel
  5629. def on_splash_changed(self, state):
  5630. settings = QSettings("Open Source", "FlatCAM")
  5631. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5632. # This will write the setting to the platform specific storage.
  5633. del settings
  5634. def on_tab_rmb_click(self, checked):
  5635. self.ui.notebook.set_detachable(val=checked)
  5636. self.defaults["global_tabs_detachable"] = checked
  5637. self.ui.plot_tab_area.set_detachable(val=checked)
  5638. self.defaults["global_tabs_detachable"] = checked
  5639. def on_tab_setup_context_menu(self):
  5640. initial_checked = self.defaults["global_tabs_detachable"]
  5641. action_name = str(_("Detachable Tabs"))
  5642. action = QtWidgets.QAction(self)
  5643. action.setCheckable(True)
  5644. action.setText(action_name)
  5645. action.setChecked(initial_checked)
  5646. self.ui.notebook.tabBar.addAction(action)
  5647. self.ui.plot_tab_area.tabBar.addAction(action)
  5648. try:
  5649. action.triggered.disconnect()
  5650. except TypeError:
  5651. pass
  5652. action.triggered.connect(self.on_tab_rmb_click)
  5653. def on_deselect_all(self):
  5654. self.collection.set_all_inactive()
  5655. self.delete_selection_shape()
  5656. def on_workspace_modified(self):
  5657. # self.save_defaults(silent=True)
  5658. if self.is_legacy is True:
  5659. self.plotcanvas.delete_workspace()
  5660. self.defaults_read_form()
  5661. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5662. def on_workspace(self):
  5663. if self.ui.general_defaults_form.general_gui_group.workspace_cb.get_value():
  5664. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5665. else:
  5666. self.plotcanvas.delete_workspace()
  5667. self.defaults_read_form()
  5668. # self.save_defaults(silent=True)
  5669. def on_workspace_toggle(self):
  5670. state = False if self.ui.general_defaults_form.general_gui_group.workspace_cb.get_value() else True
  5671. try:
  5672. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  5673. except TypeError:
  5674. pass
  5675. self.ui.general_defaults_form.general_gui_group.workspace_cb.set_value(state)
  5676. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  5677. self.on_workspace()
  5678. def on_layout(self, index=None, lay=None):
  5679. """
  5680. Set the toolbars layout (location)
  5681. :param index:
  5682. :param lay: type of layout to be set on the toolbard
  5683. :return: None
  5684. """
  5685. self.report_usage("on_layout()")
  5686. if lay:
  5687. current_layout = lay
  5688. else:
  5689. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5690. lay_settings = QSettings("Open Source", "FlatCAM")
  5691. lay_settings.setValue('layout', current_layout)
  5692. # This will write the setting to the platform specific storage.
  5693. del lay_settings
  5694. # first remove the toolbars:
  5695. try:
  5696. self.ui.removeToolBar(self.ui.toolbarfile)
  5697. self.ui.removeToolBar(self.ui.toolbargeo)
  5698. self.ui.removeToolBar(self.ui.toolbarview)
  5699. self.ui.removeToolBar(self.ui.toolbarshell)
  5700. self.ui.removeToolBar(self.ui.toolbartools)
  5701. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5702. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5703. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5704. self.ui.removeToolBar(self.ui.snap_toolbar)
  5705. self.ui.removeToolBar(self.ui.toolbarshell)
  5706. except Exception:
  5707. pass
  5708. if current_layout == 'standard':
  5709. # ## TOOLBAR INSTALLATION # ##
  5710. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5711. self.ui.toolbarfile.setObjectName('File_TB')
  5712. self.ui.addToolBar(self.ui.toolbarfile)
  5713. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5714. self.ui.toolbargeo.setObjectName('Edit_TB')
  5715. self.ui.addToolBar(self.ui.toolbargeo)
  5716. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5717. self.ui.toolbarview.setObjectName('View_TB')
  5718. self.ui.addToolBar(self.ui.toolbarview)
  5719. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5720. self.ui.toolbarshell.setObjectName('Shell_TB')
  5721. self.ui.addToolBar(self.ui.toolbarshell)
  5722. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5723. self.ui.toolbartools.setObjectName('Tools_TB')
  5724. self.ui.addToolBar(self.ui.toolbartools)
  5725. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5726. # self.ui.exc_edit_toolbar.setVisible(False)
  5727. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5728. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5729. self.ui.addToolBarBreak()
  5730. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5731. # self.ui.geo_edit_toolbar.setVisible(False)
  5732. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5733. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5734. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5735. # self.ui.grb_edit_toolbar.setVisible(False)
  5736. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5737. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5738. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5739. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5740. # self.ui.snap_toolbar.setMaximumHeight(30)
  5741. self.ui.addToolBar(self.ui.snap_toolbar)
  5742. self.ui.corner_snap_btn.setVisible(False)
  5743. self.ui.snap_magnet.setVisible(False)
  5744. elif current_layout == 'compact':
  5745. # ## TOOLBAR INSTALLATION # ##
  5746. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5747. self.ui.toolbarfile.setObjectName('File_TB')
  5748. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5749. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5750. self.ui.toolbargeo.setObjectName('Edit_TB')
  5751. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5752. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5753. self.ui.toolbarshell.setObjectName('Shell_TB')
  5754. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5755. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5756. self.ui.toolbartools.setObjectName('Tools_TB')
  5757. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5758. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5759. # self.ui.geo_edit_toolbar.setVisible(False)
  5760. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5761. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5762. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5763. self.ui.toolbarview.setObjectName('View_TB')
  5764. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5765. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5766. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5767. # self.ui.grb_edit_toolbar.setVisible(False)
  5768. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5769. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5770. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5771. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5772. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5773. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5774. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5775. self.ui.snap_toolbar.setMaximumHeight(30)
  5776. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5777. self.ui.corner_snap_btn.setVisible(True)
  5778. self.ui.snap_magnet.setVisible(True)
  5779. # add all the actions to the toolbars
  5780. self.ui.populate_toolbars()
  5781. # reconnect all the signals to the toolbar actions
  5782. self.connect_toolbar_signals()
  5783. self.ui.grid_snap_btn.setChecked(True)
  5784. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5785. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5786. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5787. self.ui.grid_gap_link_cb.setChecked(True)
  5788. def on_cursor_type(self, val):
  5789. """
  5790. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5791. :return: None
  5792. """
  5793. self.app_cursor.enabled = False
  5794. if val == 'small':
  5795. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5796. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5797. self.app_cursor = self.plotcanvas.new_cursor()
  5798. else:
  5799. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5800. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5801. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5802. if self.ui.grid_snap_btn.isChecked():
  5803. self.app_cursor.enabled = True
  5804. else:
  5805. self.app_cursor.enabled = False
  5806. def on_cnc_custom_parameters(self, signal_text):
  5807. if signal_text == 'Parameters':
  5808. return
  5809. else:
  5810. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5811. def on_save_button(self, save_to_file=True):
  5812. log.debug("App.on_save_button() --> Applying preferences to file.")
  5813. # Preferences saved, update flag
  5814. self.preferences_changed_flag = False
  5815. # Preferences save, update the color of the Preferences Tab text
  5816. for idx in range(self.ui.plot_tab_area.count()):
  5817. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5818. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5819. self.inform.emit('%s' % _("Preferences applied."))
  5820. if save_to_file:
  5821. self.save_defaults(silent=False)
  5822. # load the defaults so they are updated into the app
  5823. self.load_defaults(filename='current_defaults')
  5824. # Re-fresh project options
  5825. self.on_options_app2project()
  5826. settgs = QSettings("Open Source", "FlatCAM")
  5827. # save the notebook font size
  5828. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5829. settgs.setValue('notebook_font_size', fsize)
  5830. # save the axis font size
  5831. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5832. settgs.setValue('axis_font_size', g_fsize)
  5833. # save the textbox font size
  5834. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5835. settgs.setValue('textbox_font_size', tb_fsize)
  5836. settgs.setValue(
  5837. 'machinist',
  5838. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  5839. )
  5840. # This will write the setting to the platform specific storage.
  5841. del settgs
  5842. def on_pref_close_button(self):
  5843. # Preferences saved, update flag
  5844. self.preferences_changed_flag = False
  5845. try:
  5846. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_plot_area_tab_closed)
  5847. except TypeError:
  5848. pass
  5849. self.defaults_write_form()
  5850. # Preferences save, update the color of the Preferences Tab text
  5851. for idx in range(self.ui.plot_tab_area.count()):
  5852. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5853. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5854. self.ui.plot_tab_area.closeTab(idx)
  5855. break
  5856. self.inform.emit('%s' % _("Preferences closed without saving."))
  5857. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  5858. def on_tool_add_keypress(self):
  5859. # ## Current application units in Upper Case
  5860. self.units = self.defaults['units'].upper()
  5861. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5862. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5863. if notebook_widget_name == 'selected_tab':
  5864. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5865. # Tool add works for Geometry only if Advanced is True in Preferences
  5866. if self.defaults["global_app_level"] == 'a':
  5867. tool_add_popup = FCInputDialog(title="New Tool ...",
  5868. text='Enter a Tool Diameter:',
  5869. min=0.0000, max=99.9999, decimals=4)
  5870. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5871. val, ok = tool_add_popup.get_value()
  5872. if ok:
  5873. if float(val) == 0:
  5874. self.inform.emit('[WARNING_NOTCL] %s' %
  5875. _("Please enter a tool diameter with non-zero value, in Float format."))
  5876. return
  5877. self.collection.get_active().on_tool_add(dia=float(val))
  5878. else:
  5879. self.inform.emit('[WARNING_NOTCL] %s...' %
  5880. _("Adding Tool cancelled"))
  5881. else:
  5882. msgbox = QtWidgets.QMessageBox()
  5883. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5884. "Go to Preferences -> General - Show Advanced Options."))
  5885. msgbox.setWindowTitle("Tool adding ...")
  5886. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5887. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5888. msgbox.setDefaultButton(bt_ok)
  5889. msgbox.exec_()
  5890. # work only if the notebook tab on focus is the Tools_Tab
  5891. if notebook_widget_name == 'tool_tab':
  5892. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5893. # and only if the tool is NCC Tool
  5894. if tool_widget == self.ncclear_tool.toolName:
  5895. self.ncclear_tool.on_add_tool_by_key()
  5896. # and only if the tool is Paint Area Tool
  5897. elif tool_widget == self.paint_tool.toolName:
  5898. self.paint_tool.on_add_tool_by_key()
  5899. # and only if the tool is Solder Paste Dispensing Tool
  5900. elif tool_widget == self.paste_tool.toolName:
  5901. self.paste_tool.on_add_tool_by_key()
  5902. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5903. # See description bellow.
  5904. def on_delete_keypress(self):
  5905. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5906. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5907. if notebook_widget_name == 'selected_tab':
  5908. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5909. self.collection.get_active().on_tool_delete()
  5910. # work only if the notebook tab on focus is the Tools_Tab
  5911. elif notebook_widget_name == 'tool_tab':
  5912. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5913. # and only if the tool is NCC Tool
  5914. if tool_widget == self.ncclear_tool.toolName:
  5915. self.ncclear_tool.on_tool_delete()
  5916. # and only if the tool is Paint Tool
  5917. elif tool_widget == self.paint_tool.toolName:
  5918. self.paint_tool.on_tool_delete()
  5919. # and only if the tool is Solder Paste Dispensing Tool
  5920. elif tool_widget == self.paste_tool.toolName:
  5921. self.paste_tool.on_tool_delete()
  5922. else:
  5923. self.on_delete()
  5924. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5925. # some screens you have to be careful where you hover with your mouse.
  5926. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5927. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5928. # Complicated, I know :)
  5929. def on_delete(self):
  5930. """
  5931. Delete the currently selected FlatCAMObjs.
  5932. :return: None
  5933. """
  5934. self.report_usage("on_delete()")
  5935. response = None
  5936. bt_ok = None
  5937. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5938. # a geometry object before we update it.
  5939. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5940. and self.grb_editor.editor_active is False:
  5941. if self.defaults["global_delete_confirmation"] is True:
  5942. msgbox = QtWidgets.QMessageBox()
  5943. msgbox.setWindowTitle(_("Delete objects"))
  5944. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5945. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5946. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5947. "the selected objects?"))
  5948. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5949. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5950. msgbox.setDefaultButton(bt_ok)
  5951. msgbox.exec_()
  5952. response = msgbox.clickedButton()
  5953. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5954. if self.collection.get_active():
  5955. self.log.debug("App.on_delete()")
  5956. while self.collection.get_active():
  5957. obj_active = self.collection.get_active()
  5958. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5959. if isinstance(obj_active, FlatCAMGerber):
  5960. for el in obj_active.mark_shapes:
  5961. obj_active.mark_shapes[el].clear(update=True)
  5962. obj_active.mark_shapes[el].enabled = False
  5963. # obj_active.mark_shapes[el] = None
  5964. del el
  5965. elif isinstance(obj_active, FlatCAMCNCjob):
  5966. try:
  5967. obj_active.annotation.clear(update=True)
  5968. obj_active.annotation.enabled = False
  5969. except AttributeError:
  5970. pass
  5971. self.delete_first_selected()
  5972. self.inform.emit('%s...' %
  5973. _("Object(s) deleted"))
  5974. # make sure that the selection shape is deleted, too
  5975. self.delete_selection_shape()
  5976. else:
  5977. self.inform.emit(_("Failed. No object(s) selected..."))
  5978. else:
  5979. self.inform.emit(_("Save the work in Editor and try again ..."))
  5980. def delete_first_selected(self):
  5981. # Keep this for later
  5982. try:
  5983. sel_obj = self.collection.get_active()
  5984. name = sel_obj.options["name"]
  5985. isPlotted = sel_obj.options["plot"]
  5986. except AttributeError:
  5987. self.log.debug("Nothing selected for deletion")
  5988. return
  5989. if self.is_legacy is True:
  5990. # Remove plot only if the object was plotted otherwise delaxes will fail
  5991. if isPlotted:
  5992. try:
  5993. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5994. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5995. except Exception as e:
  5996. log.debug("App.delete_first_selected() --> %s" % str(e))
  5997. self.plotcanvas.auto_adjust_axes()
  5998. # Remove from dictionary
  5999. self.collection.delete_active()
  6000. # Clear form
  6001. self.setup_component_editor()
  6002. self.inform.emit('%s: %s' %
  6003. (_("Object deleted"), name))
  6004. def on_set_origin(self):
  6005. """
  6006. Set the origin to the left mouse click position
  6007. :return: None
  6008. """
  6009. # display the message for the user
  6010. # and ask him to click on the desired position
  6011. self.report_usage("on_set_origin()")
  6012. def origin_replot():
  6013. def worker_task():
  6014. with self.proc_container.new('%s...' % _("Plotting")):
  6015. for obj in self.collection.get_list():
  6016. obj.plot()
  6017. self.plotcanvas.fit_view()
  6018. if self.is_legacy:
  6019. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  6020. else:
  6021. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  6022. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6023. self.inform.emit(_('Click to set the origin ...'))
  6024. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  6025. # first disconnect it as it may have been used by something else
  6026. try:
  6027. self.replot_signal.disconnect()
  6028. except TypeError:
  6029. pass
  6030. self.replot_signal[list].connect(origin_replot)
  6031. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  6032. """
  6033. :param event:
  6034. :param location:
  6035. :param noplot:
  6036. :param use_thread:
  6037. :return:
  6038. """
  6039. noplot_sig = noplot
  6040. def worker_task():
  6041. with self.proc_container.new(_("Setting Origin...")):
  6042. for obj in self.collection.get_list():
  6043. obj.offset((x, y))
  6044. self.object_changed.emit(obj)
  6045. # Update the object bounding box options
  6046. a, b, c, d = obj.bounds()
  6047. obj.options['xmin'] = a
  6048. obj.options['ymin'] = b
  6049. obj.options['xmax'] = c
  6050. obj.options['ymax'] = d
  6051. self.inform.emit('[success] %s...' %
  6052. _('Origin set'))
  6053. if noplot_sig is False:
  6054. self.replot_signal.emit([])
  6055. if location is not None:
  6056. if len(location) != 2:
  6057. self.inform.emit('[ERROR_NOTCL] %s...' %
  6058. _("Origin coordinates specified but incomplete."))
  6059. return 'fail'
  6060. x, y = location
  6061. if use_thread is True:
  6062. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6063. else:
  6064. worker_task()
  6065. self.should_we_save = True
  6066. return
  6067. if event.button == 1:
  6068. if self.is_legacy is False:
  6069. event_pos = event.pos
  6070. else:
  6071. event_pos = (event.xdata, event.ydata)
  6072. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6073. if self.grid_status() == True:
  6074. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6075. else:
  6076. pos = pos_canvas
  6077. x = 0 - pos[0]
  6078. y = 0 - pos[1]
  6079. if use_thread is True:
  6080. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6081. else:
  6082. worker_task()
  6083. self.should_we_save = True
  6084. def on_jump_to(self, custom_location=None, fit_center=True):
  6085. """
  6086. Jump to a location by setting the mouse cursor location
  6087. :return:
  6088. """
  6089. self.report_usage("on_jump_to()")
  6090. # if self.is_legacy is True:
  6091. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  6092. # return
  6093. if not custom_location:
  6094. dia_box_location = None
  6095. try:
  6096. dia_box_location = eval(self.clipboard.text())
  6097. except Exception:
  6098. pass
  6099. if type(dia_box_location) == tuple:
  6100. dia_box_location = str(dia_box_location)
  6101. else:
  6102. dia_box_location = None
  6103. dia_box = Dialog_box(title=_("Jump to ..."),
  6104. label=_("Enter the coordinates in format X,Y:"),
  6105. icon=QtGui.QIcon('share/jump_to16.png'),
  6106. initial_text=dia_box_location)
  6107. if dia_box.ok is True:
  6108. try:
  6109. location = eval(dia_box.location)
  6110. if not isinstance(location, tuple):
  6111. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  6112. return
  6113. except Exception:
  6114. return
  6115. else:
  6116. return
  6117. else:
  6118. location = custom_location
  6119. units = self.defaults['units'].upper()
  6120. if fit_center:
  6121. self.plotcanvas.fit_center(loc=location)
  6122. cursor = QtGui.QCursor()
  6123. if self.is_legacy is False:
  6124. # I don't know where those differences come from but they are constant for the current
  6125. # execution of the application and they are multiples of a value around 0.0263mm.
  6126. # In a random way sometimes they are more sometimes they are less
  6127. # if units == 'MM':
  6128. # cal_factor = 0.0263
  6129. # else:
  6130. # cal_factor = 0.0263 / 25.4
  6131. cal_location = (location[0], location[1])
  6132. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6133. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  6134. j_pos = (
  6135. int(canvas_origin.x() + round(jump_loc[0])),
  6136. int(canvas_origin.y() + round(jump_loc[1]))
  6137. )
  6138. cursor.setPos(j_pos[0], j_pos[1])
  6139. else:
  6140. # find the canvas origin which is in the top left corner
  6141. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6142. # determine the coordinates for the lowest left point of the canvas
  6143. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6144. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6145. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6146. # canvas) and the point (width, height) is in the top-right location
  6147. loc = self.plotcanvas.axes.transData.transform_point(location)
  6148. j_pos = (
  6149. int(x0 + loc[0]),
  6150. int(y0 - loc[1])
  6151. )
  6152. cursor.setPos(j_pos[0], j_pos[1])
  6153. self.plotcanvas.mouse = [location[0], location[1]]
  6154. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  6155. if self.grid_status():
  6156. # Update cursor
  6157. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6158. symbol='++', edge_color=self.cursor_color_3D,
  6159. size=self.defaults["global_cursor_size"])
  6160. # Set the position label
  6161. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6162. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6163. # Set the relative position label
  6164. dx = location[0] - float(self.rel_point1[0])
  6165. dy = location[1] - float(self.rel_point1[1])
  6166. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6167. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6168. self.inform.emit('[success] %s' % _("Done."))
  6169. return location
  6170. def on_copy_object(self):
  6171. self.report_usage("on_copy_object()")
  6172. def initialize(obj_init, app):
  6173. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6174. try:
  6175. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6176. except AttributeError:
  6177. pass
  6178. try:
  6179. obj_init.apertures = deepcopy(obj.apertures)
  6180. except AttributeError:
  6181. pass
  6182. try:
  6183. if obj.tools:
  6184. obj_init.tools = deepcopy(obj.tools)
  6185. except Exception as e:
  6186. log.debug("App.on_copy_object() --> %s" % str(e))
  6187. try:
  6188. obj_init.source_file = deepcopy(obj.source_file)
  6189. except (AttributeError, TypeError):
  6190. pass
  6191. def initialize_excellon(obj_init, app):
  6192. obj_init.source_file = deepcopy(obj.source_file)
  6193. obj_init.tools = deepcopy(obj.tools)
  6194. # drills are offset, so they need to be deep copied
  6195. obj_init.drills = deepcopy(obj.drills)
  6196. # slots are offset, so they need to be deep copied
  6197. obj_init.slots = deepcopy(obj.slots)
  6198. obj_init.create_geometry()
  6199. def initialize_script(obj_init, app_obj):
  6200. obj_init.source_file = deepcopy(obj.source_file)
  6201. def initialize_document(obj_init, app_obj):
  6202. obj_init.source_file = deepcopy(obj.source_file)
  6203. for obj in self.collection.get_selected():
  6204. obj_name = obj.options["name"]
  6205. try:
  6206. if isinstance(obj, FlatCAMExcellon):
  6207. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  6208. elif isinstance(obj, FlatCAMGerber):
  6209. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  6210. elif isinstance(obj, FlatCAMGeometry):
  6211. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  6212. elif isinstance(obj, FlatCAMScript):
  6213. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  6214. elif isinstance(obj, FlatCAMDocument):
  6215. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  6216. except Exception as e:
  6217. return "Operation failed: %s" % str(e)
  6218. def on_copy_object2(self, custom_name):
  6219. def initialize_geometry(obj_init, app):
  6220. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6221. try:
  6222. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6223. except AttributeError:
  6224. pass
  6225. try:
  6226. obj_init.apertures = deepcopy(obj.apertures)
  6227. except AttributeError:
  6228. pass
  6229. try:
  6230. if obj.tools:
  6231. obj_init.tools = deepcopy(obj.tools)
  6232. except Exception as ee:
  6233. log.debug("on_copy_object2() --> %s" % str(ee))
  6234. def initialize_gerber(obj_init, app):
  6235. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6236. obj_init.apertures = deepcopy(obj.apertures)
  6237. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  6238. def initialize_excellon(obj_init, app):
  6239. obj_init.tools = deepcopy(obj.tools)
  6240. # drills are offset, so they need to be deep copied
  6241. obj_init.drills = deepcopy(obj.drills)
  6242. # slots are offset, so they need to be deep copied
  6243. obj_init.slots = deepcopy(obj.slots)
  6244. obj_init.create_geometry()
  6245. for obj in self.collection.get_selected():
  6246. obj_name = obj.options["name"]
  6247. try:
  6248. if isinstance(obj, FlatCAMExcellon):
  6249. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  6250. elif isinstance(obj, FlatCAMGerber):
  6251. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  6252. elif isinstance(obj, FlatCAMGeometry):
  6253. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  6254. except Exception as e:
  6255. return "Operation failed: %s" % str(e)
  6256. def on_rename_object(self, text):
  6257. self.report_usage("on_rename_object()")
  6258. named_obj = self.collection.get_active()
  6259. for obj in named_obj:
  6260. if obj is list:
  6261. self.on_rename_object(text)
  6262. else:
  6263. try:
  6264. obj.options['name'] = text
  6265. except Exception as e:
  6266. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  6267. def convert_any2geo(self):
  6268. self.report_usage("convert_any2geo()")
  6269. def initialize(obj_init, app):
  6270. obj_init.solid_geometry = obj.solid_geometry
  6271. try:
  6272. obj_init.follow_geometry = obj.follow_geometry
  6273. except AttributeError:
  6274. pass
  6275. try:
  6276. obj_init.apertures = obj.apertures
  6277. except AttributeError:
  6278. pass
  6279. try:
  6280. if obj.tools:
  6281. obj_init.tools = obj.tools
  6282. except AttributeError:
  6283. pass
  6284. def initialize_excellon(obj_init, app):
  6285. # objs = self.collection.get_selected()
  6286. # FlatCAMGeometry.merge(objs, obj)
  6287. solid_geo = []
  6288. for tool in obj.tools:
  6289. for geo in obj.tools[tool]['solid_geometry']:
  6290. solid_geo.append(geo)
  6291. obj_init.solid_geometry = deepcopy(solid_geo)
  6292. if not self.collection.get_selected():
  6293. log.warning("App.convert_any2geo --> No object selected")
  6294. self.inform.emit('[WARNING_NOTCL] %s' %
  6295. _("No object is selected. Select an object and try again."))
  6296. return
  6297. for obj in self.collection.get_selected():
  6298. obj_name = obj.options["name"]
  6299. try:
  6300. if isinstance(obj, FlatCAMExcellon):
  6301. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6302. else:
  6303. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6304. except Exception as e:
  6305. return "Operation failed: %s" % str(e)
  6306. def convert_any2gerber(self):
  6307. self.report_usage("convert_any2gerber()")
  6308. def initialize_geometry(obj_init, app):
  6309. apertures = {}
  6310. apid = 0
  6311. apertures[str(apid)] = {}
  6312. apertures[str(apid)]['geometry'] = []
  6313. for obj_orig in obj.solid_geometry:
  6314. new_elem = dict()
  6315. new_elem['solid'] = obj_orig
  6316. try:
  6317. new_elem['follow'] = obj_orig.exterior
  6318. except AttributeError:
  6319. pass
  6320. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6321. apertures[str(apid)]['size'] = 0.0
  6322. apertures[str(apid)]['type'] = 'C'
  6323. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6324. obj_init.apertures = deepcopy(apertures)
  6325. def initialize_excellon(obj_init, app):
  6326. apertures = {}
  6327. apid = 10
  6328. for tool in obj.tools:
  6329. apertures[str(apid)] = {}
  6330. apertures[str(apid)]['geometry'] = []
  6331. for geo in obj.tools[tool]['solid_geometry']:
  6332. new_el = dict()
  6333. new_el['solid'] = geo
  6334. new_el['follow'] = geo.exterior
  6335. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6336. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6337. apertures[str(apid)]['type'] = 'C'
  6338. apid += 1
  6339. # create solid_geometry
  6340. solid_geometry = []
  6341. for apid in apertures:
  6342. for geo_el in apertures[apid]['geometry']:
  6343. solid_geometry.append(geo_el['solid'])
  6344. solid_geometry = MultiPolygon(solid_geometry)
  6345. solid_geometry = solid_geometry.buffer(0.0000001)
  6346. obj_init.solid_geometry = deepcopy(solid_geometry)
  6347. obj_init.apertures = deepcopy(apertures)
  6348. # clear the working objects (perhaps not necessary due of Python GC)
  6349. apertures.clear()
  6350. if not self.collection.get_selected():
  6351. log.warning("App.convert_any2gerber --> No object selected")
  6352. self.inform.emit('[WARNING_NOTCL] %s' %
  6353. _("No object is selected. Select an object and try again."))
  6354. return
  6355. for obj in self.collection.get_selected():
  6356. obj_name = obj.options["name"]
  6357. try:
  6358. if isinstance(obj, FlatCAMExcellon):
  6359. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6360. elif isinstance(obj, FlatCAMGeometry):
  6361. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6362. else:
  6363. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6364. except Exception as e:
  6365. return "Operation failed: %s" % str(e)
  6366. def abort_all_tasks(self):
  6367. if self.abort_flag is False:
  6368. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6369. self.abort_flag = True
  6370. def app_is_idle(self):
  6371. if self.abort_flag:
  6372. self.inform.emit('[WARNING_NOTCL] %s' %
  6373. _("The current task was gracefully closed on user request..."))
  6374. self.abort_flag = False
  6375. def on_selectall(self):
  6376. self.report_usage("on_selectall()")
  6377. # delete the possible selection box around a possible selected object
  6378. self.delete_selection_shape()
  6379. for name in self.collection.get_names():
  6380. self.collection.set_active(name)
  6381. curr_sel_obj = self.collection.get_by_name(name)
  6382. # create the selection box around the selected object
  6383. if self.defaults['global_selection_shape'] is True:
  6384. self.draw_selection_shape(curr_sel_obj)
  6385. def on_preferences(self):
  6386. """
  6387. Adds the Preferences in a Tab in Plot Area
  6388. :return:
  6389. """
  6390. # add the tab if it was closed
  6391. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6392. # delete the absolute and relative position and messages in the infobar
  6393. self.ui.position_label.setText("")
  6394. self.ui.rel_position_label.setText("")
  6395. # Switch plot_area to preferences page
  6396. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6397. # self.ui.show()
  6398. # detect changes in the preferences
  6399. for idx in range(self.ui.pref_tab_area.count()):
  6400. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6401. try:
  6402. try:
  6403. tb.textEdited.disconnect(self.on_preferences_edited)
  6404. except (TypeError, AttributeError):
  6405. pass
  6406. tb.textEdited.connect(self.on_preferences_edited)
  6407. except AttributeError:
  6408. pass
  6409. try:
  6410. try:
  6411. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6412. except (TypeError, AttributeError):
  6413. pass
  6414. tb.modificationChanged.connect(self.on_preferences_edited)
  6415. except AttributeError:
  6416. pass
  6417. try:
  6418. try:
  6419. tb.toggled.disconnect(self.on_preferences_edited)
  6420. except (TypeError, AttributeError):
  6421. pass
  6422. tb.toggled.connect(self.on_preferences_edited)
  6423. except AttributeError:
  6424. pass
  6425. try:
  6426. try:
  6427. tb.valueChanged.disconnect(self.on_preferences_edited)
  6428. except (TypeError, AttributeError):
  6429. pass
  6430. tb.valueChanged.connect(self.on_preferences_edited)
  6431. except AttributeError:
  6432. pass
  6433. try:
  6434. try:
  6435. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6436. except (TypeError, AttributeError):
  6437. pass
  6438. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6439. except AttributeError:
  6440. pass
  6441. def on_preferences_edited(self):
  6442. self.inform.emit('[WARNING_NOTCL] %s' %
  6443. _("Preferences edited but not saved."))
  6444. for idx in range(self.ui.plot_tab_area.count()):
  6445. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  6446. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6447. self.preferences_changed_flag = True
  6448. def on_tools_database(self):
  6449. """
  6450. Adds the Tools Database in a Tab in Plot Area
  6451. :return:
  6452. """
  6453. for idx in range(self.ui.plot_tab_area.count()):
  6454. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6455. # there can be only one instance of Tools Database at one time
  6456. return
  6457. self.tools_db_tab = ToolsDB(
  6458. app=self,
  6459. parent=self.ui,
  6460. callback_on_edited=self.on_tools_db_edited,
  6461. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  6462. )
  6463. # add the tab if it was closed
  6464. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  6465. self.tools_db_tab.setObjectName("database_tab")
  6466. # delete the absolute and relative position and messages in the infobar
  6467. self.ui.position_label.setText("")
  6468. self.ui.rel_position_label.setText("")
  6469. # Switch plot_area to preferences page
  6470. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  6471. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  6472. self.tools_db_tab.ui_connect()
  6473. def on_tools_db_edited(self):
  6474. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  6475. for idx in range(self.ui.plot_tab_area.count()):
  6476. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6477. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6478. self.tools_db_changed_flag = True
  6479. def on_geometry_tool_add_from_db_executed(self, tool):
  6480. """
  6481. Here add the tool from DB in the selected geometry object
  6482. :return:
  6483. """
  6484. tool_from_db = deepcopy(tool)
  6485. obj = self.collection.get_active()
  6486. if isinstance(obj, FlatCAMGeometry):
  6487. obj.on_tool_from_db_inserted(tool=tool_from_db)
  6488. for idx in range(self.ui.plot_tab_area.count()):
  6489. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6490. wdg = self.ui.plot_tab_area.widget(idx)
  6491. wdg.deleteLater()
  6492. self.ui.plot_tab_area.removeTab(idx)
  6493. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  6494. else:
  6495. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  6496. def on_plot_area_tab_closed(self, title):
  6497. if title == _("Preferences"):
  6498. # disconnect
  6499. for idx in range(self.ui.pref_tab_area.count()):
  6500. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6501. try:
  6502. tb.textEdited.disconnect(self.on_preferences_edited)
  6503. except (TypeError, AttributeError):
  6504. pass
  6505. try:
  6506. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6507. except (TypeError, AttributeError):
  6508. pass
  6509. try:
  6510. tb.toggled.disconnect(self.on_preferences_edited)
  6511. except (TypeError, AttributeError):
  6512. pass
  6513. try:
  6514. tb.valueChanged.disconnect(self.on_preferences_edited)
  6515. except (TypeError, AttributeError):
  6516. pass
  6517. try:
  6518. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6519. except (TypeError, AttributeError):
  6520. pass
  6521. if self.preferences_changed_flag is True:
  6522. msgbox = QtWidgets.QMessageBox()
  6523. msgbox.setText(_("One or more values are changed.\n"
  6524. "Do you want to save the Preferences?"))
  6525. msgbox.setWindowTitle(_("Save Preferences"))
  6526. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6527. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6528. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6529. msgbox.setDefaultButton(bt_yes)
  6530. msgbox.exec_()
  6531. response = msgbox.clickedButton()
  6532. if response == bt_yes:
  6533. self.on_save_button(save_to_file=True)
  6534. self.inform.emit('[success] %s' % _("Preferences saved."))
  6535. else:
  6536. self.preferences_changed_flag = False
  6537. self.inform.emit('')
  6538. return
  6539. if title == _("Tools Database"):
  6540. # disconnect the signals from the table widget in tab
  6541. self.tools_db_tab.ui_disconnect()
  6542. if self.tools_db_changed_flag is True:
  6543. msgbox = QtWidgets.QMessageBox()
  6544. msgbox.setText(_("One or more Tools are edited.\n"
  6545. "Do you want to update the Tools Database?"))
  6546. msgbox.setWindowTitle(_("Save Tools Database"))
  6547. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6548. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6549. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6550. msgbox.setDefaultButton(bt_yes)
  6551. msgbox.exec_()
  6552. response = msgbox.clickedButton()
  6553. if response == bt_yes:
  6554. self.tools_db_tab.on_save_tools_db()
  6555. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  6556. else:
  6557. self.tools_db_changed_flag = False
  6558. self.inform.emit('')
  6559. return
  6560. self.tools_db_tab.deleteLater()
  6561. if title == _("Code Editor"):
  6562. self.toggle_codeeditor = False
  6563. if title == _("Bookmarks Manager"):
  6564. self.book_dialog_tab.rebuild_actions()
  6565. self.book_dialog_tab.deleteLater()
  6566. def on_flipy(self):
  6567. self.report_usage("on_flipy()")
  6568. obj_list = self.collection.get_selected()
  6569. xminlist = []
  6570. yminlist = []
  6571. xmaxlist = []
  6572. ymaxlist = []
  6573. if not obj_list:
  6574. self.inform.emit('[WARNING_NOTCL] %s' %
  6575. _("No object selected to Flip on Y axis."))
  6576. else:
  6577. try:
  6578. # first get a bounding box to fit all
  6579. for obj in obj_list:
  6580. xmin, ymin, xmax, ymax = obj.bounds()
  6581. xminlist.append(xmin)
  6582. yminlist.append(ymin)
  6583. xmaxlist.append(xmax)
  6584. ymaxlist.append(ymax)
  6585. # get the minimum x,y and maximum x,y for all objects selected
  6586. xminimal = min(xminlist)
  6587. yminimal = min(yminlist)
  6588. xmaximal = max(xmaxlist)
  6589. ymaximal = max(ymaxlist)
  6590. px = 0.5 * (xminimal + xmaximal)
  6591. py = 0.5 * (yminimal + ymaximal)
  6592. # execute mirroring
  6593. for obj in obj_list:
  6594. obj.mirror('X', [px, py])
  6595. obj.plot()
  6596. self.object_changed.emit(obj)
  6597. self.inform.emit('[success] %s' %
  6598. _("Flip on Y axis done."))
  6599. except Exception as e:
  6600. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6601. return
  6602. def on_flipx(self):
  6603. self.report_usage("on_flipx()")
  6604. obj_list = self.collection.get_selected()
  6605. xminlist = []
  6606. yminlist = []
  6607. xmaxlist = []
  6608. ymaxlist = []
  6609. if not obj_list:
  6610. self.inform.emit('[WARNING_NOTCL] %s' %
  6611. _("No object selected to Flip on X axis."))
  6612. else:
  6613. try:
  6614. # first get a bounding box to fit all
  6615. for obj in obj_list:
  6616. xmin, ymin, xmax, ymax = obj.bounds()
  6617. xminlist.append(xmin)
  6618. yminlist.append(ymin)
  6619. xmaxlist.append(xmax)
  6620. ymaxlist.append(ymax)
  6621. # get the minimum x,y and maximum x,y for all objects selected
  6622. xminimal = min(xminlist)
  6623. yminimal = min(yminlist)
  6624. xmaximal = max(xmaxlist)
  6625. ymaximal = max(ymaxlist)
  6626. px = 0.5 * (xminimal + xmaximal)
  6627. py = 0.5 * (yminimal + ymaximal)
  6628. # execute mirroring
  6629. for obj in obj_list:
  6630. obj.mirror('Y', [px, py])
  6631. obj.plot()
  6632. self.object_changed.emit(obj)
  6633. self.inform.emit('[success] %s' %
  6634. _("Flip on X axis done."))
  6635. except Exception as e:
  6636. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6637. return
  6638. def on_rotate(self, silent=False, preset=None):
  6639. self.report_usage("on_rotate()")
  6640. obj_list = self.collection.get_selected()
  6641. xminlist = []
  6642. yminlist = []
  6643. xmaxlist = []
  6644. ymaxlist = []
  6645. if not obj_list:
  6646. self.inform.emit('[WARNING_NOTCL] %s' %
  6647. _("No object selected to Rotate."))
  6648. else:
  6649. if silent is False:
  6650. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6651. min=-360, max=360, decimals=4,
  6652. init_val=float(self.defaults['tools_transform_rotate']))
  6653. num, ok = rotatebox.get_value()
  6654. else:
  6655. num = preset
  6656. ok = True
  6657. if ok:
  6658. try:
  6659. # first get a bounding box to fit all
  6660. for obj in obj_list:
  6661. xmin, ymin, xmax, ymax = obj.bounds()
  6662. xminlist.append(xmin)
  6663. yminlist.append(ymin)
  6664. xmaxlist.append(xmax)
  6665. ymaxlist.append(ymax)
  6666. # get the minimum x,y and maximum x,y for all objects selected
  6667. xminimal = min(xminlist)
  6668. yminimal = min(yminlist)
  6669. xmaximal = max(xmaxlist)
  6670. ymaximal = max(ymaxlist)
  6671. px = 0.5 * (xminimal + xmaximal)
  6672. py = 0.5 * (yminimal + ymaximal)
  6673. for sel_obj in obj_list:
  6674. sel_obj.rotate(-float(num), point=(px, py))
  6675. sel_obj.plot()
  6676. self.object_changed.emit(sel_obj)
  6677. self.inform.emit('[success] %s' %
  6678. _("Rotation done."))
  6679. except Exception as e:
  6680. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  6681. return
  6682. def on_skewx(self):
  6683. self.report_usage("on_skewx()")
  6684. obj_list = self.collection.get_selected()
  6685. xminlist = []
  6686. yminlist = []
  6687. if not obj_list:
  6688. self.inform.emit('[WARNING_NOTCL] %s' %
  6689. _("No object selected to Skew/Shear on X axis."))
  6690. else:
  6691. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6692. min=-360, max=360, decimals=4,
  6693. init_val=float(self.defaults['tools_transform_skew_x']))
  6694. num, ok = skewxbox.get_value()
  6695. if ok:
  6696. # first get a bounding box to fit all
  6697. for obj in obj_list:
  6698. xmin, ymin, xmax, ymax = obj.bounds()
  6699. xminlist.append(xmin)
  6700. yminlist.append(ymin)
  6701. # get the minimum x,y and maximum x,y for all objects selected
  6702. xminimal = min(xminlist)
  6703. yminimal = min(yminlist)
  6704. for obj in obj_list:
  6705. obj.skew(num, 0, point=(xminimal, yminimal))
  6706. obj.plot()
  6707. self.object_changed.emit(obj)
  6708. self.inform.emit('[success] %s' %
  6709. _("Skew on X axis done."))
  6710. def on_skewy(self):
  6711. self.report_usage("on_skewy()")
  6712. obj_list = self.collection.get_selected()
  6713. xminlist = []
  6714. yminlist = []
  6715. if not obj_list:
  6716. self.inform.emit('[WARNING_NOTCL] %s' %
  6717. _("No object selected to Skew/Shear on Y axis."))
  6718. else:
  6719. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6720. min=-360, max=360, decimals=4,
  6721. init_val=float(self.defaults['tools_transform_skew_y']))
  6722. num, ok = skewybox.get_value()
  6723. if ok:
  6724. # first get a bounding box to fit all
  6725. for obj in obj_list:
  6726. xmin, ymin, xmax, ymax = obj.bounds()
  6727. xminlist.append(xmin)
  6728. yminlist.append(ymin)
  6729. # get the minimum x,y and maximum x,y for all objects selected
  6730. xminimal = min(xminlist)
  6731. yminimal = min(yminlist)
  6732. for obj in obj_list:
  6733. obj.skew(0, num, point=(xminimal, yminimal))
  6734. obj.plot()
  6735. self.object_changed.emit(obj)
  6736. self.inform.emit('[success] %s' %
  6737. _("Skew on Y axis done."))
  6738. def on_plots_updated(self):
  6739. """
  6740. Callback used to report when the plots have changed.
  6741. Adjust axes and zooms to fit.
  6742. :return: None
  6743. """
  6744. if self.is_legacy is False:
  6745. self.plotcanvas.update() # TODO: Need update canvas?
  6746. else:
  6747. self.plotcanvas.auto_adjust_axes()
  6748. self.on_zoom_fit(None)
  6749. self.collection.update_view()
  6750. # self.inform.emit(_("Plots updated ..."))
  6751. # TODO: Rework toolbar 'clear', 'replot' functions
  6752. def on_toolbar_replot(self):
  6753. """
  6754. Callback for toolbar button. Re-plots all objects.
  6755. :return: None
  6756. """
  6757. self.report_usage("on_toolbar_replot")
  6758. self.log.debug("on_toolbar_replot()")
  6759. try:
  6760. self.collection.get_active().read_form()
  6761. except AttributeError:
  6762. self.log.debug("on_toolbar_replot(): AttributeError")
  6763. pass
  6764. self.plot_all()
  6765. def on_row_activated(self, index):
  6766. if index.isValid():
  6767. if index.internalPointer().parent_item != self.collection.root_item:
  6768. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6769. self.collection.on_item_activated(index)
  6770. def on_row_selected(self, obj_name):
  6771. # this is a special string; when received it will make all entries unchecked
  6772. # it mean we clicked outside of the items and deselected all
  6773. if obj_name == 'none':
  6774. for act in self.ui.menuobjects.actions():
  6775. act.setChecked(False)
  6776. return
  6777. # get the name of the selected objects and add them to a list
  6778. name_list = list()
  6779. for obj in self.collection.get_selected():
  6780. name_list.append(obj.options['name'])
  6781. # set all actions as unchecked but the ones selected make them checked
  6782. for act in self.ui.menuobjects.actions():
  6783. act.setChecked(False)
  6784. if act.text() in name_list:
  6785. act.setChecked(True)
  6786. def on_collection_updated(self, obj, state, old_name):
  6787. """
  6788. Create a menu from the object loaded in the collection.
  6789. TODO: should use the collection model to do this
  6790. :param obj: object that was changd (added, deleted, renamed)
  6791. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6792. :param old_name: the old name of the object before the action that triggered this slot happened
  6793. :return: None
  6794. """
  6795. icon_files = {
  6796. "gerber": "share/flatcam_icon16.png",
  6797. "excellon": "share/drill16.png",
  6798. "cncjob": "share/cnc16.png",
  6799. "geometry": "share/geometry16.png",
  6800. "script": "share/script_new16.png",
  6801. "document": "share/notes16_1.png"
  6802. }
  6803. if state == 'append':
  6804. for act in self.ui.menuobjects.actions():
  6805. try:
  6806. act.triggered.disconnect()
  6807. except TypeError:
  6808. pass
  6809. self.ui.menuobjects.clear()
  6810. gerber_list = list()
  6811. exc_list = list()
  6812. cncjob_list = list()
  6813. geo_list = list()
  6814. script_list = list()
  6815. doc_list = list()
  6816. for name in self.collection.get_names():
  6817. obj_named = self.collection.get_by_name(name)
  6818. if obj_named.kind == 'gerber':
  6819. gerber_list.append(name)
  6820. elif obj_named.kind == 'excellon':
  6821. exc_list.append(name)
  6822. elif obj_named.kind == 'cncjob':
  6823. cncjob_list.append(name)
  6824. elif obj_named.kind == 'geometry':
  6825. geo_list.append(name)
  6826. elif obj_named.kind == 'script':
  6827. script_list.append(name)
  6828. elif obj_named.kind == 'document':
  6829. doc_list.append(name)
  6830. def add_act(o_name):
  6831. obj_for_icon = self.collection.get_by_name(o_name)
  6832. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6833. add_action.setCheckable(True)
  6834. add_action.setText(o_name)
  6835. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6836. add_action.triggered.connect(
  6837. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  6838. self.collection.set_inactive(o_name))
  6839. self.ui.menuobjects.addAction(add_action)
  6840. for name in gerber_list:
  6841. add_act(name)
  6842. self.ui.menuobjects.addSeparator()
  6843. for name in exc_list:
  6844. add_act(name)
  6845. self.ui.menuobjects.addSeparator()
  6846. for name in cncjob_list:
  6847. add_act(name)
  6848. self.ui.menuobjects.addSeparator()
  6849. for name in geo_list:
  6850. add_act(name)
  6851. self.ui.menuobjects.addSeparator()
  6852. for name in script_list:
  6853. add_act(name)
  6854. self.ui.menuobjects.addSeparator()
  6855. for name in doc_list:
  6856. add_act(name)
  6857. self.ui.menuobjects.addSeparator()
  6858. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6859. QtGui.QIcon('share/select_all.png'),
  6860. _('Select All')
  6861. )
  6862. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6863. QtGui.QIcon('share/deselect_all32.png'),
  6864. _('Deselect All')
  6865. )
  6866. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6867. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6868. elif state == 'delete':
  6869. for act in self.ui.menuobjects.actions():
  6870. if act.text() == obj.options['name']:
  6871. try:
  6872. act.triggered.disconnect()
  6873. except TypeError:
  6874. pass
  6875. self.ui.menuobjects.removeAction(act)
  6876. break
  6877. elif state == 'rename':
  6878. for act in self.ui.menuobjects.actions():
  6879. if act.text() == old_name:
  6880. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6881. add_action.setText(obj.options['name'])
  6882. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6883. add_action.triggered.connect(
  6884. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  6885. self.collection.set_inactive(obj.options['name']))
  6886. self.ui.menuobjects.insertAction(act, add_action)
  6887. try:
  6888. act.triggered.disconnect()
  6889. except TypeError:
  6890. pass
  6891. self.ui.menuobjects.removeAction(act)
  6892. break
  6893. elif state == 'delete_all':
  6894. for act in self.ui.menuobjects.actions():
  6895. try:
  6896. act.triggered.disconnect()
  6897. except TypeError:
  6898. pass
  6899. self.ui.menuobjects.clear()
  6900. self.ui.menuobjects.addSeparator()
  6901. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6902. QtGui.QIcon('share/select_all.png'),
  6903. _('Select All')
  6904. )
  6905. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6906. QtGui.QIcon('share/deselect_all32.png'),
  6907. _('Deselect All')
  6908. )
  6909. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6910. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6911. def on_objects_selection(self, on_off):
  6912. obj_list = self.collection.get_names()
  6913. if on_off is True:
  6914. self.collection.set_all_active()
  6915. for act in self.ui.menuobjects.actions():
  6916. try:
  6917. act.setChecked(True)
  6918. except Exception:
  6919. pass
  6920. if obj_list:
  6921. self.inform.emit('[selected] %s' % _("All objects are selected."))
  6922. else:
  6923. self.collection.set_all_inactive()
  6924. for act in self.ui.menuobjects.actions():
  6925. try:
  6926. act.setChecked(False)
  6927. except Exception:
  6928. pass
  6929. if obj_list:
  6930. self.inform.emit('%s' % _("Objects selection is cleared."))
  6931. else:
  6932. self.inform.emit('')
  6933. def grid_status(self):
  6934. if self.ui.grid_snap_btn.isChecked():
  6935. return True
  6936. else:
  6937. return False
  6938. def populate_cmenu_grids(self):
  6939. units = self.defaults['units'].lower()
  6940. self.ui.cmenu_gridmenu.clear()
  6941. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6942. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6943. grid_toggle.setCheckable(True)
  6944. if self.grid_status() == True:
  6945. grid_toggle.setChecked(True)
  6946. else:
  6947. grid_toggle.setChecked(False)
  6948. self.ui.cmenu_gridmenu.addSeparator()
  6949. for grid in sorted_list:
  6950. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6951. action.triggered.connect(self.set_grid)
  6952. self.ui.cmenu_gridmenu.addSeparator()
  6953. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6954. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6955. grid_add.triggered.connect(self.on_grid_add)
  6956. grid_delete.triggered.connect(self.on_grid_delete)
  6957. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6958. def set_grid(self):
  6959. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6960. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6961. def on_grid_add(self):
  6962. # ## Current application units in lower Case
  6963. units = self.defaults['units'].lower()
  6964. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6965. text=_('Enter a Grid Value:'),
  6966. min=0.0000, max=99.9999, decimals=4)
  6967. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6968. val, ok = grid_add_popup.get_value()
  6969. if ok:
  6970. if float(val) == 0:
  6971. self.inform.emit('[WARNING_NOTCL] %s' %
  6972. _("Please enter a grid value with non-zero value, in Float format."))
  6973. return
  6974. else:
  6975. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6976. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6977. self.inform.emit('[success] %s...' %
  6978. _("New Grid added"))
  6979. else:
  6980. self.inform.emit('[WARNING_NOTCL] %s...' %
  6981. _("Grid already exists"))
  6982. else:
  6983. self.inform.emit('[WARNING_NOTCL] %s...' %
  6984. _("Adding New Grid cancelled"))
  6985. def on_grid_delete(self):
  6986. # ## Current application units in lower Case
  6987. units = self.defaults['units'].lower()
  6988. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6989. text='Enter a Grid Value:',
  6990. min=0.0000, max=99.9999, decimals=4)
  6991. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6992. val, ok = grid_del_popup.get_value()
  6993. if ok:
  6994. if float(val) == 0:
  6995. self.inform.emit('[WARNING_NOTCL] %s' %
  6996. _("Please enter a grid value with non-zero value, in Float format."))
  6997. return
  6998. else:
  6999. try:
  7000. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  7001. except ValueError:
  7002. self.inform.emit('[ERROR_NOTCL]%s...' %
  7003. _(" Grid Value does not exist"))
  7004. return
  7005. self.inform.emit('[success] %s...' %
  7006. _("Grid Value deleted"))
  7007. else:
  7008. self.inform.emit('[WARNING_NOTCL] %s...' %
  7009. _("Delete Grid value cancelled"))
  7010. def on_shortcut_list(self):
  7011. self.report_usage("on_shortcut_list()")
  7012. # add the tab if it was closed
  7013. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  7014. # delete the absolute and relative position and messages in the infobar
  7015. self.ui.position_label.setText("")
  7016. self.ui.rel_position_label.setText("")
  7017. # Switch plot_area to preferences page
  7018. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  7019. # self.ui.show()
  7020. def on_select_tab(self, name):
  7021. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  7022. if self.ui.splitter.sizes()[0] == 0:
  7023. self.ui.splitter.setSizes([1, 1])
  7024. else:
  7025. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  7026. self.ui.splitter.setSizes([0, 1])
  7027. if name == 'project':
  7028. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7029. elif name == 'selected':
  7030. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7031. elif name == 'tool':
  7032. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  7033. def on_copy_name(self):
  7034. self.report_usage("on_copy_name()")
  7035. obj = self.collection.get_active()
  7036. try:
  7037. name = obj.options["name"]
  7038. except AttributeError:
  7039. log.debug("on_copy_name() --> No object selected to copy it's name")
  7040. self.inform.emit('[WARNING_NOTCL]%s' %
  7041. _(" No object selected to copy it's name"))
  7042. return
  7043. self.clipboard.setText(name)
  7044. self.inform.emit(_("Name copied on clipboard ..."))
  7045. def on_mouse_click_over_plot(self, event):
  7046. """
  7047. Default actions are:
  7048. :param event: Contains information about the event, like which button
  7049. was clicked, the pixel coordinates and the axes coordinates.
  7050. :return: None
  7051. """
  7052. self.pos = []
  7053. if self.is_legacy is False:
  7054. event_pos = event.pos
  7055. if self.defaults["global_pan_button"] == '2':
  7056. pan_button = 2
  7057. else:
  7058. pan_button = 3
  7059. # Set the mouse button for panning
  7060. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7061. else:
  7062. event_pos = (event.xdata, event.ydata)
  7063. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7064. if self.defaults["global_pan_button"] == '2':
  7065. pan_button = 3
  7066. else:
  7067. pan_button = 2
  7068. # So it can receive key presses
  7069. self.plotcanvas.native.setFocus()
  7070. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7071. if self.grid_status() == True:
  7072. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  7073. else:
  7074. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  7075. try:
  7076. if event.button == 1:
  7077. # Reset here the relative coordinates so there is a new reference on the click position
  7078. if self.rel_point1 is None:
  7079. self.rel_point1 = self.pos
  7080. else:
  7081. self.rel_point2 = copy(self.rel_point1)
  7082. self.rel_point1 = self.pos
  7083. self.on_mouse_move_over_plot(event, origin_click=True)
  7084. except Exception as e:
  7085. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  7086. def on_mouse_double_click_over_plot(self, event):
  7087. if event.button == 1:
  7088. self.doubleclick = True
  7089. def on_mouse_move_over_plot(self, event, origin_click=None):
  7090. """
  7091. Callback for the mouse motion event over the plot.
  7092. :param event: Contains information about the event.
  7093. :param origin_click
  7094. :return: None
  7095. """
  7096. if self.is_legacy is False:
  7097. event_pos = event.pos
  7098. if self.defaults["global_pan_button"] == '2':
  7099. pan_button = 2
  7100. else:
  7101. pan_button = 3
  7102. self.event_is_dragging = event.is_dragging
  7103. else:
  7104. event_pos = (event.xdata, event.ydata)
  7105. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7106. if self.defaults["global_pan_button"] == '2':
  7107. pan_button = 3
  7108. else:
  7109. pan_button = 2
  7110. self.event_is_dragging = self.plotcanvas.is_dragging
  7111. # So it can receive key presses
  7112. self.plotcanvas.native.setFocus()
  7113. self.pos_jump = event_pos
  7114. self.ui.popMenu.mouse_is_panning = False
  7115. if not origin_click:
  7116. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  7117. if event.button == pan_button and self.event_is_dragging == 1:
  7118. self.ui.popMenu.mouse_is_panning = True
  7119. return
  7120. if self.rel_point1 is not None:
  7121. try: # May fail in case mouse not within axes
  7122. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7123. if self.grid_status() == True:
  7124. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7125. # Update cursor
  7126. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  7127. symbol='++', edge_color=self.cursor_color_3D,
  7128. size=self.defaults["global_cursor_size"])
  7129. else:
  7130. pos = (pos_canvas[0], pos_canvas[1])
  7131. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  7132. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  7133. dx = pos[0] - float(self.rel_point1[0])
  7134. dy = pos[1] - float(self.rel_point1[1])
  7135. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  7136. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  7137. self.mouse = [pos[0], pos[1]]
  7138. # if the mouse is moved and the LMB is clicked then the action is a selection
  7139. if self.event_is_dragging == 1 and event.button == 1:
  7140. self.delete_selection_shape()
  7141. if dx < 0:
  7142. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  7143. face_color=self.defaults['global_alt_sel_fill'])
  7144. self.selection_type = False
  7145. elif dx > 0:
  7146. self.draw_moving_selection_shape(self.pos, pos)
  7147. self.selection_type = True
  7148. else:
  7149. self.selection_type = None
  7150. # hover effect - enabled in Preferences -> General -> GUI Settings
  7151. if self.defaults['global_hover']:
  7152. for obj in self.collection.get_list():
  7153. try:
  7154. # select the object(s) only if it is enabled (plotted)
  7155. if obj.options['plot']:
  7156. if obj not in self.collection.get_selected():
  7157. poly_obj = Polygon(
  7158. [(obj.options['xmin'], obj.options['ymin']),
  7159. (obj.options['xmax'], obj.options['ymin']),
  7160. (obj.options['xmax'], obj.options['ymax']),
  7161. (obj.options['xmin'], obj.options['ymax'])]
  7162. )
  7163. if Point(pos).within(poly_obj):
  7164. if obj.isHovering is False:
  7165. obj.isHovering = True
  7166. obj.notHovering = True
  7167. # create the selection box around the selected object
  7168. self.draw_hover_shape(obj, color='#d1e0e0FF')
  7169. else:
  7170. if obj.notHovering is True:
  7171. obj.notHovering = False
  7172. obj.isHovering = False
  7173. self.delete_hover_shape()
  7174. except Exception:
  7175. # the Exception here will happen if we try to select on screen and we have an
  7176. # newly (and empty) just created Geometry or Excellon object that do not have the
  7177. # xmin, xmax, ymin, ymax options.
  7178. # In this case poly_obj creation (see above) will fail
  7179. pass
  7180. except Exception:
  7181. self.ui.position_label.setText("")
  7182. self.ui.rel_position_label.setText("")
  7183. self.mouse = None
  7184. def on_mouse_click_release_over_plot(self, event):
  7185. """
  7186. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  7187. and has been registered in ''self.__init__()''.
  7188. :param event: contains information about the event.
  7189. :return:
  7190. """
  7191. if self.is_legacy is False:
  7192. event_pos = event.pos
  7193. right_button = 2
  7194. else:
  7195. event_pos = (event.xdata, event.ydata)
  7196. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7197. right_button = 3
  7198. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7199. if self.grid_status() == True:
  7200. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7201. else:
  7202. pos = (pos_canvas[0], pos_canvas[1])
  7203. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  7204. # canvas menu
  7205. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  7206. self.cursor = QtGui.QCursor()
  7207. self.populate_cmenu_grids()
  7208. self.ui.popMenu.popup(self.cursor.pos())
  7209. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  7210. # selection and then select a type of selection ("enclosing" or "touching")
  7211. if event.button == 1: # left click
  7212. modifiers = QtWidgets.QApplication.keyboardModifiers()
  7213. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  7214. if modifiers == QtCore.Qt.ShiftModifier:
  7215. # do not auto open the Project Tab
  7216. self.click_noproject = True
  7217. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  7218. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  7219. return
  7220. if self.doubleclick is True:
  7221. self.doubleclick = False
  7222. if self.collection.get_selected():
  7223. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7224. if self.ui.splitter.sizes()[0] == 0:
  7225. self.ui.splitter.setSizes([1, 1])
  7226. try:
  7227. # delete the selection shape(S) as it may be in the way
  7228. self.delete_selection_shape()
  7229. self.delete_hover_shape()
  7230. except Exception as e:
  7231. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  7232. return
  7233. else:
  7234. if self.selection_type is not None:
  7235. try:
  7236. self.selection_area_handler(self.pos, pos, self.selection_type)
  7237. self.selection_type = None
  7238. except Exception as e:
  7239. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  7240. return
  7241. else:
  7242. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  7243. if key_modifier == QtCore.Qt.ShiftModifier:
  7244. mod_key = 'Shift'
  7245. elif key_modifier == QtCore.Qt.ControlModifier:
  7246. mod_key = 'Control'
  7247. else:
  7248. mod_key = None
  7249. try:
  7250. if mod_key == self.defaults["global_mselect_key"]:
  7251. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  7252. # deselect, and if it's not selected then it will be selected
  7253. # If there is no active command (self.command_active is None) then we check if we clicked
  7254. # on a object by checking the bounding limits against mouse click position
  7255. if self.command_active is None:
  7256. self.select_objects(key='CTRL')
  7257. self.delete_hover_shape()
  7258. else:
  7259. # If there is no active command (self.command_active is None) then we check if we clicked
  7260. # on a object by checking the bounding limits against mouse click position
  7261. if self.command_active is None:
  7262. self.select_objects()
  7263. self.delete_hover_shape()
  7264. except Exception as e:
  7265. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  7266. return
  7267. def selection_area_handler(self, start_pos, end_pos, sel_type):
  7268. """
  7269. :param start_pos: mouse position when the selection LMB click was done
  7270. :param end_pos: mouse position when the left mouse button is released
  7271. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  7272. :return:
  7273. """
  7274. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  7275. # delete previous selection shape
  7276. self.delete_selection_shape()
  7277. # make all objects inactive
  7278. self.collection.set_all_inactive()
  7279. for obj in self.collection.get_list():
  7280. try:
  7281. # select the object(s) only if it is enabled (plotted)
  7282. if obj.options['plot']:
  7283. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  7284. (obj.options['xmax'], obj.options['ymin']),
  7285. (obj.options['xmax'], obj.options['ymax']),
  7286. (obj.options['xmin'], obj.options['ymax'])])
  7287. if sel_type is True:
  7288. if poly_obj.within(poly_selection):
  7289. # create the selection box around the selected object
  7290. if self.defaults['global_selection_shape'] is True:
  7291. self.draw_selection_shape(obj)
  7292. self.collection.set_active(obj.options['name'])
  7293. else:
  7294. if poly_selection.intersects(poly_obj):
  7295. # create the selection box around the selected object
  7296. if self.defaults['global_selection_shape'] is True:
  7297. self.draw_selection_shape(obj)
  7298. self.collection.set_active(obj.options['name'])
  7299. except Exception as e:
  7300. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  7301. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  7302. # In this case poly_obj creation (see above) will fail
  7303. log.debug("App.selection_area_handler() --> %s" % str(e))
  7304. def select_objects(self, key=None):
  7305. """
  7306. Will select objects clicked on canvas
  7307. :param key: for future use in cumulative selection
  7308. :return:
  7309. """
  7310. # list where we store the overlapped objects under our mouse left click position
  7311. objects_under_the_click_list = []
  7312. # Populate the list with the overlapped objects on the click position
  7313. curr_x, curr_y = self.pos
  7314. for obj in self.all_objects_list:
  7315. # FlatCAMScript and FlatCAMDocument objects can't be selected
  7316. if isinstance(obj, FlatCAMScript) or isinstance(obj, FlatCAMDocument):
  7317. continue
  7318. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  7319. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  7320. if obj.options['name'] not in objects_under_the_click_list:
  7321. if obj.options['plot']:
  7322. # add objects to the objects_under_the_click list only if the object is plotted
  7323. # (active and not disabled)
  7324. objects_under_the_click_list.append(obj.options['name'])
  7325. try:
  7326. if objects_under_the_click_list:
  7327. curr_sel_obj = self.collection.get_active()
  7328. # case when there is only an object under the click and we toggle it
  7329. if len(objects_under_the_click_list) == 1:
  7330. if curr_sel_obj is None:
  7331. self.collection.set_active(objects_under_the_click_list[0])
  7332. curr_sel_obj = self.collection.get_active()
  7333. # create the selection box around the selected object
  7334. if self.defaults['global_selection_shape'] is True:
  7335. self.draw_selection_shape(curr_sel_obj)
  7336. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  7337. self.on_objects_selection(False)
  7338. self.delete_selection_shape()
  7339. self.collection.set_active(objects_under_the_click_list[0])
  7340. curr_sel_obj = self.collection.get_active()
  7341. # create the selection box around the selected object
  7342. if self.defaults['global_selection_shape'] is True:
  7343. self.draw_selection_shape(curr_sel_obj)
  7344. self.selected_message(curr_sel_obj=curr_sel_obj)
  7345. else:
  7346. self.on_objects_selection(False)
  7347. self.delete_selection_shape()
  7348. if self.call_source != 'app':
  7349. self.call_source = 'app'
  7350. self.selected_message(curr_sel_obj=curr_sel_obj)
  7351. else:
  7352. # If there is no selected object
  7353. # make active the first element of the overlapped objects list
  7354. if self.collection.get_active() is None:
  7355. self.collection.set_active(objects_under_the_click_list[0])
  7356. name_sel_obj = self.collection.get_active().options['name']
  7357. # In case that there is a selected object but it is not in the overlapped object list
  7358. # make that object inactive and activate the first element in the overlapped object list
  7359. if name_sel_obj not in objects_under_the_click_list:
  7360. self.collection.set_inactive(name_sel_obj)
  7361. name_sel_obj = objects_under_the_click_list[0]
  7362. self.collection.set_active(name_sel_obj)
  7363. else:
  7364. sel_idx = objects_under_the_click_list.index(name_sel_obj)
  7365. self.collection.set_all_inactive()
  7366. self.collection.set_active(objects_under_the_click_list[(sel_idx + 1) %
  7367. len(objects_under_the_click_list)])
  7368. curr_sel_obj = self.collection.get_active()
  7369. # delete the possible selection box around a possible selected object
  7370. self.delete_selection_shape()
  7371. # create the selection box around the selected object
  7372. if self.defaults['global_selection_shape'] is True:
  7373. self.draw_selection_shape(curr_sel_obj)
  7374. self.selected_message(curr_sel_obj=curr_sel_obj)
  7375. else:
  7376. # deselect everything
  7377. self.on_objects_selection(False)
  7378. # delete the possible selection box around a possible selected object
  7379. self.delete_selection_shape()
  7380. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  7381. # only when working on App
  7382. if self.call_source == 'app':
  7383. if self.click_noproject is False:
  7384. # if the Tool Tab is in focus don't change focus to Project Tab
  7385. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  7386. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7387. else:
  7388. # restore auto open the Project Tab
  7389. self.click_noproject = False
  7390. # delete any text in the status bar, implicitly the last object name that was selected
  7391. # self.inform.emit("")
  7392. else:
  7393. self.call_source = 'app'
  7394. except Exception as e:
  7395. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  7396. def selected_message(self, curr_sel_obj):
  7397. if curr_sel_obj:
  7398. if curr_sel_obj.kind == 'gerber':
  7399. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7400. color='green', name=str(curr_sel_obj.options['name'])))
  7401. elif curr_sel_obj.kind == 'excellon':
  7402. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7403. color='brown', name=str(curr_sel_obj.options['name'])))
  7404. elif curr_sel_obj.kind == 'cncjob':
  7405. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7406. color='blue', name=str(curr_sel_obj.options['name'])))
  7407. elif curr_sel_obj.kind == 'geometry':
  7408. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7409. color='red', name=str(curr_sel_obj.options['name'])))
  7410. def delete_hover_shape(self):
  7411. self.hover_shapes.clear()
  7412. self.hover_shapes.redraw()
  7413. def draw_hover_shape(self, sel_obj, color=None):
  7414. """
  7415. :param sel_obj: the object for which the hover shape must be drawn
  7416. :return:
  7417. """
  7418. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7419. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7420. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7421. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7422. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  7423. if self.defaults['units'].upper() == 'MM':
  7424. hover_rect = hover_rect.buffer(-0.1)
  7425. hover_rect = hover_rect.buffer(0.2)
  7426. else:
  7427. hover_rect = hover_rect.buffer(-0.00393)
  7428. hover_rect = hover_rect.buffer(0.00787)
  7429. # if color:
  7430. # face = Color(color)
  7431. # face.alpha = 0.2
  7432. # outline = Color(color, alpha=0.8)
  7433. # else:
  7434. # face = Color(self.defaults['global_sel_fill'])
  7435. # face.alpha = 0.2
  7436. # outline = self.defaults['global_sel_line']
  7437. if color:
  7438. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7439. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7440. else:
  7441. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7442. outline = self.defaults['global_sel_line']
  7443. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7444. if self.is_legacy is True:
  7445. self.hover_shapes.redraw()
  7446. def delete_selection_shape(self):
  7447. self.move_tool.sel_shapes.clear()
  7448. self.move_tool.sel_shapes.redraw()
  7449. def draw_selection_shape(self, sel_obj, color=None):
  7450. """
  7451. :param sel_obj: the object for which the selection shape must be drawn
  7452. :return:
  7453. """
  7454. if sel_obj is None:
  7455. return
  7456. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7457. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7458. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7459. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7460. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7461. if self.defaults['units'].upper() == 'MM':
  7462. sel_rect = sel_rect.buffer(-0.1)
  7463. sel_rect = sel_rect.buffer(0.2)
  7464. else:
  7465. sel_rect = sel_rect.buffer(-0.00393)
  7466. sel_rect = sel_rect.buffer(0.00787)
  7467. if color:
  7468. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7469. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7470. else:
  7471. if self.is_legacy is False:
  7472. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7473. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7474. else:
  7475. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  7476. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  7477. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7478. color=outline,
  7479. face_color=face,
  7480. update=True,
  7481. layer=0,
  7482. tolerance=None))
  7483. if self.is_legacy is True:
  7484. self.move_tool.sel_shapes.redraw()
  7485. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7486. """
  7487. :param old_coords: old coordinates
  7488. :param coords: new coordinates
  7489. :return:
  7490. """
  7491. if 'color' in kwargs:
  7492. color = kwargs['color']
  7493. else:
  7494. color = self.defaults['global_sel_line']
  7495. if 'face_color' in kwargs:
  7496. face_color = kwargs['face_color']
  7497. else:
  7498. face_color = self.defaults['global_sel_fill']
  7499. if 'face_alpha' in kwargs:
  7500. face_alpha = kwargs['face_alpha']
  7501. else:
  7502. face_alpha = 0.3
  7503. x0, y0 = old_coords
  7504. x1, y1 = coords
  7505. pt1 = (x0, y0)
  7506. pt2 = (x1, y0)
  7507. pt3 = (x1, y1)
  7508. pt4 = (x0, y1)
  7509. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7510. # color_t = Color(face_color)
  7511. # color_t.alpha = face_alpha
  7512. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7513. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7514. layer=0, tolerance=None)
  7515. if self.is_legacy is True:
  7516. self.move_tool.sel_shapes.redraw()
  7517. def on_file_new_click(self):
  7518. if self.collection.get_list() and self.should_we_save:
  7519. msgbox = QtWidgets.QMessageBox()
  7520. # msgbox.setText("<B>Save changes ...</B>")
  7521. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7522. "Creating a New project will delete them.\n"
  7523. "Do you want to Save the project?"))
  7524. msgbox.setWindowTitle(_("Save changes"))
  7525. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  7526. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7527. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7528. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7529. msgbox.setDefaultButton(bt_yes)
  7530. msgbox.exec_()
  7531. response = msgbox.clickedButton()
  7532. if response == bt_yes:
  7533. self.on_file_saveprojectas()
  7534. elif response == bt_cancel:
  7535. return
  7536. elif response == bt_no:
  7537. self.on_file_new()
  7538. else:
  7539. self.on_file_new()
  7540. self.inform.emit('[success] %s...' %
  7541. _("New Project created"))
  7542. def on_file_new(self, cli=None):
  7543. """
  7544. Callback for menu item File -> New. Returns the application to its
  7545. startup state. This method is thread-safe.
  7546. :return: None
  7547. """
  7548. self.report_usage("on_file_new")
  7549. # Remove everything from memory
  7550. App.log.debug("on_file_new()")
  7551. if self.call_source != 'app':
  7552. self.editor2object(cleanup=True)
  7553. # ## EDITOR section
  7554. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7555. self.exc_editor = FlatCAMExcEditor(self)
  7556. self.grb_editor = FlatCAMGrbEditor(self)
  7557. # Clear pool
  7558. self.clear_pool()
  7559. for obj in self.collection.get_list():
  7560. # delete shapes left drawn from mark shape_collections, if any
  7561. if isinstance(obj, FlatCAMGerber):
  7562. try:
  7563. obj.mark_shapes.enabled = False
  7564. obj.mark_shapes.clear(update=True)
  7565. except AttributeError:
  7566. pass
  7567. # also delete annotation shapes, if any
  7568. elif isinstance(obj, FlatCAMCNCjob):
  7569. try:
  7570. obj.annotation.enabled = False
  7571. obj.annotation.clear(update=True)
  7572. except AttributeError:
  7573. pass
  7574. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7575. self.init_tcl()
  7576. self.delete_selection_shape()
  7577. self.collection.delete_all()
  7578. self.setup_component_editor()
  7579. # Clear project filename
  7580. self.project_filename = None
  7581. # Load the application defaults
  7582. self.load_defaults(filename='current_defaults')
  7583. # Re-fresh project options
  7584. self.on_options_app2project()
  7585. # Init Tools
  7586. self.init_tools()
  7587. if cli is None:
  7588. # Close any Tabs opened in the Plot Tab Area section
  7589. for index in range(self.ui.plot_tab_area.count()):
  7590. self.ui.plot_tab_area.closeTab(index)
  7591. # for whatever reason previous command does not close the last tab so I do it manually
  7592. self.ui.plot_tab_area.closeTab(0)
  7593. # # And then add again the Plot Area
  7594. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7595. self.ui.plot_tab_area.protectTab(0)
  7596. # take the focus of the Notebook on Project Tab.
  7597. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7598. self.set_ui_title(name=_("New Project - Not saved"))
  7599. def obj_properties(self):
  7600. """
  7601. Will launch the object Properties Tool
  7602. :return:
  7603. """
  7604. self.report_usage("obj_properties()")
  7605. self.properties_tool.run(toggle=False)
  7606. def on_project_context_save(self):
  7607. """
  7608. Wrapper, will save the object function of it's type
  7609. :return:
  7610. """
  7611. obj = self.collection.get_active()
  7612. if type(obj) == FlatCAMGeometry:
  7613. self.on_file_exportdxf()
  7614. elif type(obj) == FlatCAMExcellon:
  7615. self.on_file_saveexcellon()
  7616. elif type(obj) == FlatCAMCNCjob:
  7617. obj.on_exportgcode_button_click()
  7618. elif type(obj) == FlatCAMGerber:
  7619. self.on_file_savegerber()
  7620. elif type(obj) == FlatCAMScript:
  7621. self.on_file_savescript()
  7622. elif type(obj) == FlatCAMDocument:
  7623. self.on_file_savedocument()
  7624. def obj_move(self):
  7625. self.report_usage("obj_move()")
  7626. self.move_tool.run(toggle=False)
  7627. def on_fileopengerber(self, signal: bool = None, name=None):
  7628. """
  7629. File menu callback for opening a Gerber.
  7630. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7631. :return: None
  7632. """
  7633. self.report_usage("on_fileopengerber")
  7634. App.log.debug("on_fileopengerber()")
  7635. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7636. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7637. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7638. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7639. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7640. "*.mil);;" \
  7641. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7642. "Allegro Files (*.art);;" \
  7643. "Mentor Files (*.pho *.gdo);;" \
  7644. "All Files (*.*)"
  7645. if name is None:
  7646. try:
  7647. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7648. directory=self.get_last_folder(),
  7649. filter=_filter_)
  7650. except TypeError:
  7651. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7652. filenames = [str(filename) for filename in filenames]
  7653. else:
  7654. filenames = [name]
  7655. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7656. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7657. _("Opening Gerber file.")),
  7658. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7659. color=QtGui.QColor("gray"))
  7660. if len(filenames) == 0:
  7661. self.inform.emit('[WARNING_NOTCL] %s' %
  7662. _("Open Gerber cancelled."))
  7663. else:
  7664. for filename in filenames:
  7665. if filename != '':
  7666. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7667. def on_fileopenexcellon(self, signal: bool = None, name=None):
  7668. """
  7669. File menu callback for opening an Excellon file.
  7670. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7671. :return: None
  7672. """
  7673. self.report_usage("on_fileopenexcellon")
  7674. App.log.debug("on_fileopenexcellon()")
  7675. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7676. "All Files (*.*)"
  7677. if name is None:
  7678. try:
  7679. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7680. directory=self.get_last_folder(),
  7681. filter=_filter_)
  7682. except TypeError:
  7683. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7684. filenames = [str(filename) for filename in filenames]
  7685. else:
  7686. filenames = [str(name)]
  7687. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7688. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7689. _("Opening Excellon file.")),
  7690. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7691. color=QtGui.QColor("gray"))
  7692. if len(filenames) == 0:
  7693. self.inform.emit('[WARNING_NOTCL]%s' %
  7694. _(" Open Excellon cancelled."))
  7695. else:
  7696. for filename in filenames:
  7697. if filename != '':
  7698. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7699. def on_fileopengcode(self, signal: bool = None, name=None):
  7700. """
  7701. File menu call back for opening gcode.
  7702. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7703. :return: None
  7704. """
  7705. self.report_usage("on_fileopengcode")
  7706. App.log.debug("on_fileopengcode()")
  7707. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7708. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7709. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7710. "All Files (*.*)"
  7711. if name is None:
  7712. try:
  7713. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7714. directory=self.get_last_folder(),
  7715. filter=_filter_)
  7716. except TypeError:
  7717. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7718. filenames = [str(filename) for filename in filenames]
  7719. else:
  7720. filenames = [name]
  7721. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7722. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7723. _("Opening G-Code file.")),
  7724. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7725. color=QtGui.QColor("gray"))
  7726. if len(filenames) == 0:
  7727. self.inform.emit('[WARNING_NOTCL] %s' %
  7728. _("Open G-Code cancelled."))
  7729. else:
  7730. for filename in filenames:
  7731. if filename != '':
  7732. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  7733. def on_file_openproject(self, signal: bool = None):
  7734. """
  7735. File menu callback for opening a project.
  7736. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7737. :return: None
  7738. """
  7739. self.report_usage("on_file_openproject")
  7740. App.log.debug("on_file_openproject()")
  7741. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7742. try:
  7743. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7744. directory=self.get_last_folder(), filter=_filter_)
  7745. except TypeError:
  7746. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7747. # The Qt methods above will return a QString which can cause problems later.
  7748. # So far json.dump() will fail to serialize it.
  7749. # TODO: Improve the serialization methods and remove this fix.
  7750. filename = str(filename)
  7751. if filename == "":
  7752. self.inform.emit('[WARNING_NOTCL] %s' %
  7753. _("Open Project cancelled."))
  7754. else:
  7755. # self.worker_task.emit({'fcn': self.open_project,
  7756. # 'params': [filename]})
  7757. # The above was failing because open_project() is not
  7758. # thread safe. The new_project()
  7759. self.open_project(filename)
  7760. def on_file_openconfig(self, signal: bool = None):
  7761. """
  7762. File menu callback for opening a config file.
  7763. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7764. :return: None
  7765. """
  7766. self.report_usage("on_file_openconfig")
  7767. App.log.debug("on_file_openconfig()")
  7768. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7769. try:
  7770. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7771. directory=self.data_path, filter=_filter_)
  7772. except TypeError:
  7773. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7774. filter=_filter_)
  7775. if filename == "":
  7776. self.inform.emit('[WARNING_NOTCL] %s' %
  7777. _("Open Config cancelled."))
  7778. else:
  7779. self.open_config_file(filename)
  7780. def on_file_exportsvg(self):
  7781. """
  7782. Callback for menu item File->Export SVG.
  7783. :return: None
  7784. """
  7785. self.report_usage("on_file_exportsvg")
  7786. App.log.debug("on_file_exportsvg()")
  7787. obj = self.collection.get_active()
  7788. if obj is None:
  7789. self.inform.emit('[WARNING_NOTCL] %s' %
  7790. _("No object selected."))
  7791. msg = _("Please Select a Geometry object to export")
  7792. msgbox = QtWidgets.QMessageBox()
  7793. msgbox.setInformativeText(msg)
  7794. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7795. msgbox.setDefaultButton(bt_ok)
  7796. msgbox.exec_()
  7797. return
  7798. # Check for more compatible types and add as required
  7799. if (not isinstance(obj, FlatCAMGeometry)
  7800. and not isinstance(obj, FlatCAMGerber)
  7801. and not isinstance(obj, FlatCAMCNCjob)
  7802. and not isinstance(obj, FlatCAMExcellon)):
  7803. msg = '[ERROR_NOTCL] %s' % \
  7804. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7805. msgbox = QtWidgets.QMessageBox()
  7806. msgbox.setInformativeText(msg)
  7807. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7808. msgbox.setDefaultButton(bt_ok)
  7809. msgbox.exec_()
  7810. return
  7811. name = obj.options["name"]
  7812. _filter = "SVG File (*.svg);;All Files (*.*)"
  7813. try:
  7814. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7815. caption=_("Export SVG"),
  7816. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  7817. filter=_filter)
  7818. except TypeError:
  7819. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7820. filename = str(filename)
  7821. if filename == "":
  7822. self.inform.emit('[WARNING_NOTCL]%s' %
  7823. _(" Export SVG cancelled."))
  7824. return
  7825. else:
  7826. self.export_svg(name, filename)
  7827. if self.defaults["global_open_style"] is False:
  7828. self.file_opened.emit("SVG", filename)
  7829. self.file_saved.emit("SVG", filename)
  7830. def on_file_exportpng(self):
  7831. self.report_usage("on_file_exportpng")
  7832. App.log.debug("on_file_exportpng()")
  7833. self.date = str(datetime.today()).rpartition('.')[0]
  7834. self.date = ''.join(c for c in self.date if c not in ':-')
  7835. self.date = self.date.replace(' ', '_')
  7836. if self.is_legacy is False:
  7837. image = _screenshot()
  7838. data = np.asarray(image)
  7839. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7840. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7841. _('Data must be a 3D array with last dimension 3 or 4'))
  7842. return
  7843. filter_ = "PNG File (*.png);;All Files (*.*)"
  7844. try:
  7845. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7846. caption=_("Export PNG Image"),
  7847. directory=self.get_last_save_folder() + '/png_' + self.date,
  7848. filter=filter_)
  7849. except TypeError:
  7850. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7851. filename = str(filename)
  7852. if filename == "":
  7853. self.inform.emit(_("Export PNG cancelled."))
  7854. return
  7855. else:
  7856. if self.is_legacy is False:
  7857. write_png(filename, data)
  7858. else:
  7859. self.plotcanvas.figure.savefig(filename)
  7860. if self.defaults["global_open_style"] is False:
  7861. self.file_opened.emit("png", filename)
  7862. self.file_saved.emit("png", filename)
  7863. def on_file_savegerber(self):
  7864. """
  7865. Callback for menu item in Project context menu.
  7866. :return: None
  7867. """
  7868. self.report_usage("on_file_savegerber")
  7869. App.log.debug("on_file_savegerber()")
  7870. obj = self.collection.get_active()
  7871. if obj is None:
  7872. self.inform.emit('[WARNING_NOTCL] %s' %
  7873. _("No object selected. Please select an Gerber object to export."))
  7874. return
  7875. # Check for more compatible types and add as required
  7876. if not isinstance(obj, FlatCAMGerber):
  7877. self.inform.emit('[ERROR_NOTCL] %s' %
  7878. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7879. return
  7880. name = self.collection.get_active().options["name"]
  7881. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7882. try:
  7883. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7884. caption="Save Gerber source file",
  7885. directory=self.get_last_save_folder() + '/' + name,
  7886. filter=_filter)
  7887. except TypeError:
  7888. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7889. filename = str(filename)
  7890. if filename == "":
  7891. self.inform.emit('[WARNING_NOTCL] %s' %
  7892. _("Save Gerber source file cancelled."))
  7893. return
  7894. else:
  7895. self.save_source_file(name, filename)
  7896. if self.defaults["global_open_style"] is False:
  7897. self.file_opened.emit("Gerber", filename)
  7898. self.file_saved.emit("Gerber", filename)
  7899. def on_file_savescript(self):
  7900. """
  7901. Callback for menu item in Project context menu.
  7902. :return: None
  7903. """
  7904. self.report_usage("on_file_savescript")
  7905. App.log.debug("on_file_savescript()")
  7906. obj = self.collection.get_active()
  7907. if obj is None:
  7908. self.inform.emit('[WARNING_NOTCL] %s' %
  7909. _("No object selected. Please select an Script object to export."))
  7910. return
  7911. # Check for more compatible types and add as required
  7912. if not isinstance(obj, FlatCAMScript):
  7913. self.inform.emit('[ERROR_NOTCL] %s' %
  7914. _("Failed. Only Script objects can be saved as TCL Script files..."))
  7915. return
  7916. name = self.collection.get_active().options["name"]
  7917. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7918. try:
  7919. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7920. caption="Save Script source file",
  7921. directory=self.get_last_save_folder() + '/' + name,
  7922. filter=_filter)
  7923. except TypeError:
  7924. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  7925. filename = str(filename)
  7926. if filename == "":
  7927. self.inform.emit('[WARNING_NOTCL] %s' %
  7928. _("Save Script source file cancelled."))
  7929. return
  7930. else:
  7931. self.save_source_file(name, filename)
  7932. if self.defaults["global_open_style"] is False:
  7933. self.file_opened.emit("Script", filename)
  7934. self.file_saved.emit("Script", filename)
  7935. def on_file_savedocument(self):
  7936. """
  7937. Callback for menu item in Project context menu.
  7938. :return: None
  7939. """
  7940. self.report_usage("on_file_savedocument")
  7941. App.log.debug("on_file_savedocument()")
  7942. obj = self.collection.get_active()
  7943. if obj is None:
  7944. self.inform.emit('[WARNING_NOTCL] %s' %
  7945. _("No object selected. Please select an Document object to export."))
  7946. return
  7947. # Check for more compatible types and add as required
  7948. if not isinstance(obj, FlatCAMScript):
  7949. self.inform.emit('[ERROR_NOTCL] %s' %
  7950. _("Failed. Only Document objects can be saved as Document files..."))
  7951. return
  7952. name = self.collection.get_active().options["name"]
  7953. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7954. try:
  7955. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7956. caption="Save Document source file",
  7957. directory=self.get_last_save_folder() + '/' + name,
  7958. filter=_filter)
  7959. except TypeError:
  7960. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  7961. filename = str(filename)
  7962. if filename == "":
  7963. self.inform.emit('[WARNING_NOTCL] %s' %
  7964. _("Save Document source file cancelled."))
  7965. return
  7966. else:
  7967. self.save_source_file(name, filename)
  7968. if self.defaults["global_open_style"] is False:
  7969. self.file_opened.emit("Document", filename)
  7970. self.file_saved.emit("Document", filename)
  7971. def on_file_saveexcellon(self):
  7972. """
  7973. Callback for menu item in project context menu.
  7974. :return: None
  7975. """
  7976. self.report_usage("on_file_saveexcellon")
  7977. App.log.debug("on_file_saveexcellon()")
  7978. obj = self.collection.get_active()
  7979. if obj is None:
  7980. self.inform.emit('[WARNING_NOTCL] %s' %
  7981. _("No object selected. Please select an Excellon object to export."))
  7982. return
  7983. # Check for more compatible types and add as required
  7984. if not isinstance(obj, FlatCAMExcellon):
  7985. self.inform.emit('[ERROR_NOTCL] %s' %
  7986. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7987. return
  7988. name = self.collection.get_active().options["name"]
  7989. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7990. try:
  7991. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7992. caption=_("Save Excellon source file"),
  7993. directory=self.get_last_save_folder() + '/' + name,
  7994. filter=_filter)
  7995. except TypeError:
  7996. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7997. filename = str(filename)
  7998. if filename == "":
  7999. self.inform.emit('[WARNING_NOTCL] %s' %
  8000. _("Saving Excellon source file cancelled."))
  8001. return
  8002. else:
  8003. self.save_source_file(name, filename)
  8004. if self.defaults["global_open_style"] is False:
  8005. self.file_opened.emit("Excellon", filename)
  8006. self.file_saved.emit("Excellon", filename)
  8007. def on_file_exportexcellon(self):
  8008. """
  8009. Callback for menu item File->Export->Excellon.
  8010. :return: None
  8011. """
  8012. self.report_usage("on_file_exportexcellon")
  8013. App.log.debug("on_file_exportexcellon()")
  8014. obj = self.collection.get_active()
  8015. if obj is None:
  8016. self.inform.emit('[WARNING_NOTCL] %s' %
  8017. _("No object selected. Please Select an Excellon object to export."))
  8018. return
  8019. # Check for more compatible types and add as required
  8020. if not isinstance(obj, FlatCAMExcellon):
  8021. self.inform.emit('[ERROR_NOTCL] %s' %
  8022. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8023. return
  8024. name = self.collection.get_active().options["name"]
  8025. _filter = self.defaults["excellon_save_filters"]
  8026. try:
  8027. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8028. caption=_("Export Excellon"),
  8029. directory=self.get_last_save_folder() + '/' + name,
  8030. filter=_filter)
  8031. except TypeError:
  8032. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  8033. filename = str(filename)
  8034. if filename == "":
  8035. self.inform.emit('[WARNING_NOTCL] %s' %
  8036. _("Export Excellon cancelled."))
  8037. return
  8038. else:
  8039. used_extension = filename.rpartition('.')[2]
  8040. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  8041. self.export_excellon(name, filename)
  8042. if self.defaults["global_open_style"] is False:
  8043. self.file_opened.emit("Excellon", filename)
  8044. self.file_saved.emit("Excellon", filename)
  8045. def on_file_exportgerber(self):
  8046. """
  8047. Callback for menu item File->Export->Gerber.
  8048. :return: None
  8049. """
  8050. self.report_usage("on_file_exportgerber")
  8051. App.log.debug("on_file_exportgerber()")
  8052. obj = self.collection.get_active()
  8053. if obj is None:
  8054. self.inform.emit('[WARNING_NOTCL] %s' %
  8055. _("No object selected. Please Select an Gerber object to export."))
  8056. return
  8057. # Check for more compatible types and add as required
  8058. if not isinstance(obj, FlatCAMGerber):
  8059. self.inform.emit('[ERROR_NOTCL] %s' %
  8060. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  8061. return
  8062. name = self.collection.get_active().options["name"]
  8063. _filter_ = self.defaults['gerber_save_filters']
  8064. try:
  8065. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8066. caption=_("Export Gerber"),
  8067. directory=self.get_last_save_folder() + '/' + name,
  8068. filter=_filter_)
  8069. except TypeError:
  8070. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  8071. filename = str(filename)
  8072. if filename == "":
  8073. self.inform.emit('[WARNING_NOTCL] %s' %
  8074. _("Export Gerber cancelled."))
  8075. return
  8076. else:
  8077. used_extension = filename.rpartition('.')[2]
  8078. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  8079. self.export_gerber(name, filename)
  8080. if self.defaults["global_open_style"] is False:
  8081. self.file_opened.emit("Gerber", filename)
  8082. self.file_saved.emit("Gerber", filename)
  8083. def on_file_exportdxf(self):
  8084. """
  8085. Callback for menu item File->Export DXF.
  8086. :return: None
  8087. """
  8088. self.report_usage("on_file_exportdxf")
  8089. App.log.debug("on_file_exportdxf()")
  8090. obj = self.collection.get_active()
  8091. if obj is None:
  8092. self.inform.emit('[WARNING_NOTCL] %s' %
  8093. _("No object selected."))
  8094. msg = _("Please Select a Geometry object to export")
  8095. msgbox = QtWidgets.QMessageBox()
  8096. msgbox.setInformativeText(msg)
  8097. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8098. msgbox.setDefaultButton(bt_ok)
  8099. msgbox.exec_()
  8100. return
  8101. # Check for more compatible types and add as required
  8102. if not isinstance(obj, FlatCAMGeometry):
  8103. msg = '[ERROR_NOTCL] %s' % \
  8104. _("Only Geometry objects can be used.")
  8105. msgbox = QtWidgets.QMessageBox()
  8106. msgbox.setInformativeText(msg)
  8107. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8108. msgbox.setDefaultButton(bt_ok)
  8109. msgbox.exec_()
  8110. return
  8111. name = self.collection.get_active().options["name"]
  8112. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8113. try:
  8114. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8115. caption=_("Export DXF"),
  8116. directory=self.get_last_save_folder() + '/' + name,
  8117. filter=_filter_)
  8118. except TypeError:
  8119. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  8120. filter=_filter_)
  8121. filename = str(filename)
  8122. if filename == "":
  8123. self.inform.emit('[WARNING_NOTCL] %s' %
  8124. _("Export DXF cancelled."))
  8125. return
  8126. else:
  8127. self.export_dxf(name, filename)
  8128. if self.defaults["global_open_style"] is False:
  8129. self.file_opened.emit("DXF", filename)
  8130. self.file_saved.emit("DXF", filename)
  8131. def on_file_importsvg(self, type_of_obj):
  8132. """
  8133. Callback for menu item File->Import SVG.
  8134. :param type_of_obj: to import the SVG as Geometry or as Gerber
  8135. :type type_of_obj: str
  8136. :return: None
  8137. """
  8138. self.report_usage("on_file_importsvg")
  8139. App.log.debug("on_file_importsvg()")
  8140. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  8141. try:
  8142. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8143. directory=self.get_last_folder(), filter=_filter_)
  8144. except TypeError:
  8145. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8146. filter=_filter_)
  8147. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8148. type_of_obj = "geometry"
  8149. filenames = [str(filename) for filename in filenames]
  8150. if len(filenames) == 0:
  8151. self.inform.emit('[WARNING_NOTCL] %s' %
  8152. _("Open SVG cancelled."))
  8153. else:
  8154. for filename in filenames:
  8155. if filename != '':
  8156. self.worker_task.emit({'fcn': self.import_svg,
  8157. 'params': [filename, type_of_obj]})
  8158. def on_file_importdxf(self, type_of_obj):
  8159. """
  8160. Callback for menu item File->Import DXF.
  8161. :param type_of_obj: to import the DXF as Geometry or as Gerber
  8162. :type type_of_obj: str
  8163. :return: None
  8164. """
  8165. self.report_usage("on_file_importdxf")
  8166. App.log.debug("on_file_importdxf()")
  8167. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8168. try:
  8169. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8170. directory=self.get_last_folder(),
  8171. filter=_filter_)
  8172. except TypeError:
  8173. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8174. filter=_filter_)
  8175. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8176. type_of_obj = "geometry"
  8177. filenames = [str(filename) for filename in filenames]
  8178. if len(filenames) == 0:
  8179. self.inform.emit('[WARNING_NOTCL] %s' %
  8180. _("Open DXF cancelled."))
  8181. else:
  8182. for filename in filenames:
  8183. if filename != '':
  8184. self.worker_task.emit({'fcn': self.import_dxf,
  8185. 'params': [filename, type_of_obj]})
  8186. # ###############################################################################################################
  8187. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  8188. # ###############################################################################################################
  8189. def init_code_editor(self, name):
  8190. self.text_editor_tab = TextEditor(app=self)
  8191. # add the tab if it was closed
  8192. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  8193. self.text_editor_tab.setObjectName('text_editor_tab')
  8194. # delete the absolute and relative position and messages in the infobar
  8195. self.ui.position_label.setText("")
  8196. self.ui.rel_position_label.setText("")
  8197. # first clear previous text in text editor (if any)
  8198. self.text_editor_tab.code_editor.clear()
  8199. self.text_editor_tab.code_editor.setReadOnly(False)
  8200. self.toggle_codeeditor = True
  8201. self.text_editor_tab.code_editor.completer_enable = False
  8202. self.text_editor_tab.buttonRun.hide()
  8203. # make sure to keep a reference to the code editor
  8204. self.reference_code_editor = self.text_editor_tab.code_editor
  8205. # Switch plot_area to CNCJob tab
  8206. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  8207. def on_view_source(self):
  8208. """
  8209. Called when the user wants to see the source file of the selected object
  8210. :return:
  8211. """
  8212. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  8213. self.proc_container.view.set_busy(_("Loading..."))
  8214. try:
  8215. obj = self.collection.get_active()
  8216. except Exception as e:
  8217. log.debug("App.on_view_source() --> %s" % str(e))
  8218. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8219. return 'fail'
  8220. if obj is None:
  8221. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8222. return 'fail'
  8223. flt = "All Files (*.*)"
  8224. if obj.kind == 'gerber':
  8225. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  8226. elif obj.kind == 'excellon':
  8227. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  8228. elif obj.kind == 'cncjob':
  8229. "GCode Files (*.NC);;All Files (*.*)"
  8230. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  8231. # add the tab if it was closed
  8232. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  8233. self.source_editor_tab.setObjectName('source_editor_tab')
  8234. # delete the absolute and relative position and messages in the infobar
  8235. self.ui.position_label.setText("")
  8236. self.ui.rel_position_label.setText("")
  8237. # first clear previous text in text editor (if any)
  8238. self.source_editor_tab.code_editor.clear()
  8239. self.source_editor_tab.code_editor.setReadOnly(False)
  8240. self.source_editor_tab.code_editor.completer_enable = False
  8241. self.source_editor_tab.buttonRun.hide()
  8242. # Switch plot_area to CNCJob tab
  8243. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  8244. try:
  8245. self.source_editor_tab.buttonOpen.clicked.disconnect()
  8246. except TypeError:
  8247. pass
  8248. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  8249. try:
  8250. self.source_editor_tab.buttonSave.clicked.disconnect()
  8251. except TypeError:
  8252. pass
  8253. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  8254. # then append the text from GCode to the text editor
  8255. if obj.kind == 'cncjob':
  8256. try:
  8257. file = obj.export_gcode(
  8258. preamble=self.defaults["cncjob_prepend"],
  8259. postamble=self.defaults["cncjob_append"],
  8260. to_file=True)
  8261. if file == 'fail':
  8262. return 'fail'
  8263. except AttributeError:
  8264. self.inform.emit('[WARNING_NOTCL] %s' %
  8265. _("There is no selected object for which to see it's source file code."))
  8266. return 'fail'
  8267. else:
  8268. try:
  8269. file = StringIO(obj.source_file)
  8270. except (AttributeError, TypeError):
  8271. self.inform.emit('[WARNING_NOTCL] %s' %
  8272. _("There is no selected object for which to see it's source file code."))
  8273. return 'fail'
  8274. self.source_editor_tab.t_frame.hide()
  8275. try:
  8276. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  8277. # for line in file:
  8278. # QtWidgets.QApplication.processEvents()
  8279. # proc_line = str(line).strip('\n')
  8280. # self.source_editor_tab.code_editor.append(proc_line)
  8281. except Exception as e:
  8282. log.debug('App.on_view_source() -->%s' % str(e))
  8283. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  8284. return
  8285. self.source_editor_tab.handleTextChanged()
  8286. self.source_editor_tab.t_frame.show()
  8287. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  8288. self.proc_container.view.set_idle()
  8289. # self.ui.show()
  8290. def on_toggle_code_editor(self):
  8291. self.report_usage("on_toggle_code_editor()")
  8292. if self.toggle_codeeditor is False:
  8293. self.init_code_editor(name=_("Code Editor"))
  8294. self.text_editor_tab.buttonOpen.clicked.disconnect()
  8295. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  8296. self.text_editor_tab.buttonSave.clicked.disconnect()
  8297. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  8298. else:
  8299. for idx in range(self.ui.plot_tab_area.count()):
  8300. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  8301. self.ui.plot_tab_area.closeTab(idx)
  8302. break
  8303. self.toggle_codeeditor = False
  8304. def on_code_editor_close(self):
  8305. print("closed")
  8306. self.toggle_codeeditor = False
  8307. def on_filenewscript(self, silent=False, name=None, text=None):
  8308. """
  8309. Will create a new script file and open it in the Code Editor
  8310. :param silent: if True will not display status messages
  8311. :param name: if specified will be the name of the new script
  8312. :param text: pass a source file to the newly created script to be loaded in it
  8313. :return: None
  8314. """
  8315. if silent is False:
  8316. self.inform.emit('[success] %s' %
  8317. _("New TCL script file created in Code Editor."))
  8318. # delete the absolute and relative position and messages in the infobar
  8319. self.ui.position_label.setText("")
  8320. self.ui.rel_position_label.setText("")
  8321. if name is not None:
  8322. self.new_script_object(name=name, text=text)
  8323. else:
  8324. self.new_script_object(text=text)
  8325. # script_text = script_obj.source_file
  8326. #
  8327. # self.proc_container.view.set_busy(_("Loading..."))
  8328. # script_obj.script_editor_tab.t_frame.hide()
  8329. #
  8330. # script_obj.script_editor_tab.t_frame.show()
  8331. # self.proc_container.view.set_idle()
  8332. def on_fileopenscript(self, name=None, silent=False):
  8333. """
  8334. Will open a Tcl script file into the Code Editor
  8335. :param silent: if True will not display status messages
  8336. :param name: name of a Tcl script file to open
  8337. :return:
  8338. """
  8339. self.report_usage("on_fileopenscript")
  8340. App.log.debug("on_fileopenscript()")
  8341. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8342. if name:
  8343. filenames = [name]
  8344. else:
  8345. try:
  8346. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  8347. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  8348. except TypeError:
  8349. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  8350. if len(filenames) == 0:
  8351. if silent is False:
  8352. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  8353. else:
  8354. for filename in filenames:
  8355. if filename != '':
  8356. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  8357. def on_filerunscript(self, name=None, silent=False):
  8358. """
  8359. File menu callback for loading and running a TCL script.
  8360. :param silent: if True will not display status messages
  8361. :param name: name of a Tcl script file to be run by FlatCAM
  8362. :return: None
  8363. """
  8364. self.report_usage("on_filerunscript")
  8365. App.log.debug("on_file_runscript()")
  8366. if name:
  8367. filename = name
  8368. if self.cmd_line_headless != 1:
  8369. self.splash.showMessage('%s: %ssec\n%s' %
  8370. (_("Canvas initialization started.\n"
  8371. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8372. _("Executing FlatCAMScript file.")
  8373. ),
  8374. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8375. color=QtGui.QColor("gray"))
  8376. else:
  8377. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8378. try:
  8379. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  8380. directory=self.get_last_folder(), filter=_filter_)
  8381. except TypeError:
  8382. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  8383. # The Qt methods above will return a QString which can cause problems later.
  8384. # So far json.dump() will fail to serialize it.
  8385. # TODO: Improve the serialization methods and remove this fix.
  8386. filename = str(filename)
  8387. if filename == "":
  8388. if silent is False:
  8389. self.inform.emit('[WARNING_NOTCL] %s' %
  8390. _("Run TCL script cancelled."))
  8391. else:
  8392. if self.cmd_line_headless != 1:
  8393. if self.ui.shell_dock.isHidden():
  8394. self.ui.shell_dock.show()
  8395. try:
  8396. with open(filename, "r") as tcl_script:
  8397. cmd_line_shellfile_content = tcl_script.read()
  8398. if self.cmd_line_headless != 1:
  8399. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  8400. else:
  8401. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  8402. if silent is False:
  8403. self.inform.emit('[success] %s' %
  8404. _("TCL script file opened in Code Editor and executed."))
  8405. except Exception as e:
  8406. log.debug("App.on_filerunscript() -> %s" % str(e))
  8407. sys.exit(2)
  8408. def on_file_saveproject(self, silent=False):
  8409. """
  8410. Callback for menu item File->Save Project. Saves the project to
  8411. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  8412. if set to None. The project is saved by calling ``self.save_project()``.
  8413. :param silent: if True will not display status messages
  8414. :return: None
  8415. """
  8416. self.report_usage("on_file_saveproject")
  8417. if self.project_filename is None:
  8418. self.on_file_saveprojectas()
  8419. else:
  8420. self.worker_task.emit({'fcn': self.save_project,
  8421. 'params': [self.project_filename, silent]})
  8422. if self.defaults["global_open_style"] is False:
  8423. self.file_opened.emit("project", self.project_filename)
  8424. self.file_saved.emit("project", self.project_filename)
  8425. self.set_ui_title(name=self.project_filename)
  8426. self.should_we_save = False
  8427. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  8428. """
  8429. Callback for menu item File->Save Project As... Opens a file
  8430. chooser and saves the project to the given file via
  8431. ``self.save_project()``.
  8432. :param make_copy if to be create a copy of the project; boolean
  8433. :param use_thread: if to be run in a separate thread; boolean
  8434. :param quit_action: if to be followed by quiting the application; boolean
  8435. :return: None
  8436. """
  8437. self.report_usage("on_file_saveprojectas")
  8438. self.date = str(datetime.today()).rpartition('.')[0]
  8439. self.date = ''.join(c for c in self.date if c not in ':-')
  8440. self.date = self.date.replace(' ', '_')
  8441. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  8442. try:
  8443. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8444. caption=_("Save Project As ..."),
  8445. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  8446. filter=filter_)
  8447. except TypeError:
  8448. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  8449. filename = str(filename)
  8450. if filename == '':
  8451. self.inform.emit('[WARNING_NOTCL] %s' %
  8452. _("Save Project cancelled."))
  8453. return
  8454. try:
  8455. f = open(filename, 'r')
  8456. f.close()
  8457. except IOError:
  8458. pass
  8459. if use_thread is True:
  8460. self.worker_task.emit({'fcn': self.save_project,
  8461. 'params': [filename, quit_action]})
  8462. else:
  8463. self.save_project(filename, quit_action)
  8464. # self.save_project(filename)
  8465. if self.defaults["global_open_style"] is False:
  8466. self.file_opened.emit("project", filename)
  8467. self.file_saved.emit("project", filename)
  8468. if not make_copy:
  8469. self.project_filename = filename
  8470. self.set_ui_title(name=self.project_filename)
  8471. self.should_we_save = False
  8472. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8473. """
  8474. Exports a Geometry Object to an SVG file.
  8475. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8476. :param filename: Path to the SVG file to save to.
  8477. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8478. :return:
  8479. """
  8480. self.report_usage("export_svg()")
  8481. if filename is None:
  8482. filename = self.defaults["global_last_save_folder"]
  8483. self.log.debug("export_svg()")
  8484. try:
  8485. obj = self.collection.get_by_name(str(obj_name))
  8486. except Exception:
  8487. # TODO: The return behavior has not been established... should raise exception?
  8488. return "Could not retrieve object: %s" % obj_name
  8489. with self.proc_container.new(_("Exporting SVG")) as proc:
  8490. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  8491. # Determine bounding area for svg export
  8492. bounds = obj.bounds()
  8493. size = obj.size()
  8494. # Convert everything to strings for use in the xml doc
  8495. svgwidth = str(size[0])
  8496. svgheight = str(size[1])
  8497. minx = str(bounds[0])
  8498. miny = str(bounds[1] - size[1])
  8499. uom = obj.units.lower()
  8500. # Add a SVG Header and footer to the svg output from shapely
  8501. # The transform flips the Y Axis so that everything renders
  8502. # properly within svg apps such as inkscape
  8503. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8504. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8505. svg_header += 'width="' + svgwidth + uom + '" '
  8506. svg_header += 'height="' + svgheight + uom + '" '
  8507. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8508. svg_header += '<g transform="scale(1,-1)">'
  8509. svg_footer = '</g> </svg>'
  8510. svg_elem = svg_header + exported_svg + svg_footer
  8511. # Parse the xml through a xml parser just to add line feeds
  8512. # and to make it look more pretty for the output
  8513. svgcode = parse_xml_string(svg_elem)
  8514. svgcode = svgcode.toprettyxml()
  8515. try:
  8516. with open(filename, 'w') as fp:
  8517. fp.write(svgcode)
  8518. except PermissionError:
  8519. self.inform.emit('[WARNING] %s' %
  8520. _("Permission denied, saving not possible.\n"
  8521. "Most likely another app is holding the file open and not accessible."))
  8522. return 'fail'
  8523. if self.defaults["global_open_style"] is False:
  8524. self.file_opened.emit("SVG", filename)
  8525. self.file_saved.emit("SVG", filename)
  8526. self.inform.emit('[success] %s: %s' %
  8527. (_("SVG file exported to"), filename))
  8528. def save_source_file(self, obj_name, filename, use_thread=True):
  8529. """
  8530. Exports a FlatCAM Object to an Gerber/Excellon file.
  8531. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8532. :param filename: Path to the Gerber file to save to.
  8533. :param use_thread: if to be run in a separate thread
  8534. :return:
  8535. """
  8536. self.report_usage("save source file()")
  8537. if filename is None:
  8538. filename = self.defaults["global_last_save_folder"]
  8539. self.log.debug("save source file()")
  8540. obj = self.collection.get_by_name(obj_name)
  8541. file_string = StringIO(obj.source_file)
  8542. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8543. if file_string.getvalue() == '':
  8544. self.inform.emit('[ERROR_NOTCL] %s' %
  8545. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  8546. return 'fail'
  8547. try:
  8548. with open(filename, 'w') as file:
  8549. file.writelines('G04*\n')
  8550. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8551. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8552. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8553. file.writelines('G04 Created on : %s*\n' % time_string)
  8554. for line in file_string:
  8555. file.writelines(line)
  8556. except PermissionError:
  8557. self.inform.emit('[WARNING] %s' %
  8558. _("Permission denied, saving not possible.\n"
  8559. "Most likely another app is holding the file open and not accessible."))
  8560. return 'fail'
  8561. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8562. """
  8563. Exports a Excellon Object to an Excellon file.
  8564. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8565. :param filename: Path to the Excellon file to save to.
  8566. :param local_use:
  8567. :param use_thread: if to be run in a separate thread
  8568. :return:
  8569. """
  8570. self.report_usage("export_excellon()")
  8571. if filename is None:
  8572. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  8573. self.log.debug("export_excellon()")
  8574. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8575. self.defaults["excellon_exp_decimals"]
  8576. )
  8577. if local_use is None:
  8578. try:
  8579. obj = self.collection.get_by_name(str(obj_name))
  8580. except Exception:
  8581. # TODO: The return behavior has not been established... should raise exception?
  8582. return "Could not retrieve object: %s" % obj_name
  8583. else:
  8584. obj = local_use
  8585. if not isinstance(obj, FlatCAMExcellon):
  8586. self.inform.emit('[ERROR_NOTCL] %s' %
  8587. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8588. return
  8589. # updated units
  8590. eunits = self.defaults["excellon_exp_units"]
  8591. ewhole = self.defaults["excellon_exp_integer"]
  8592. efract = self.defaults["excellon_exp_decimals"]
  8593. ezeros = self.defaults["excellon_exp_zeros"]
  8594. eformat = self.defaults["excellon_exp_format"]
  8595. slot_type = self.defaults["excellon_exp_slot_type"]
  8596. fc_units = self.defaults['units'].upper()
  8597. if fc_units == 'MM':
  8598. factor = 1 if eunits == 'METRIC' else 0.03937
  8599. else:
  8600. factor = 25.4 if eunits == 'METRIC' else 1
  8601. def make_excellon():
  8602. try:
  8603. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8604. header = 'M48\n'
  8605. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8606. (str(self.version), str(self.version_date))
  8607. header += ';Filename: %s' % str(obj_name) + '\n'
  8608. header += ';Created on : %s' % time_str + '\n'
  8609. if eformat == 'dec':
  8610. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8611. header += eunits + '\n'
  8612. for tool in obj.tools:
  8613. if eunits == 'METRIC':
  8614. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8615. tool=str(tool),
  8616. dec=2)
  8617. else:
  8618. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8619. tool=str(tool),
  8620. dec=4)
  8621. else:
  8622. if ezeros == 'LZ':
  8623. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8624. form='ndec', e_zeros='LZ', factor=factor,
  8625. slot_type=slot_type)
  8626. header += '%s,%s\n' % (eunits, 'LZ')
  8627. header += format_exc
  8628. for tool in obj.tools:
  8629. if eunits == 'METRIC':
  8630. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8631. tool=str(tool),
  8632. dec=2)
  8633. else:
  8634. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8635. tool=str(tool),
  8636. dec=4)
  8637. else:
  8638. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8639. form='ndec', e_zeros='TZ', factor=factor,
  8640. slot_type=slot_type)
  8641. header += '%s,%s\n' % (eunits, 'TZ')
  8642. header += format_exc
  8643. for tool in obj.tools:
  8644. if eunits == 'METRIC':
  8645. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8646. tool=str(tool),
  8647. dec=2)
  8648. else:
  8649. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8650. tool=str(tool),
  8651. dec=4)
  8652. header += '%\n'
  8653. footer = 'M30\n'
  8654. exported_excellon = header
  8655. exported_excellon += excellon_code
  8656. exported_excellon += footer
  8657. if local_use is None:
  8658. try:
  8659. with open(filename, 'w') as fp:
  8660. fp.write(exported_excellon)
  8661. except PermissionError:
  8662. self.inform.emit('[WARNING] %s' %
  8663. _("Permission denied, saving not possible.\n"
  8664. "Most likely another app is holding the file open and not accessible."))
  8665. return 'fail'
  8666. if self.defaults["global_open_style"] is False:
  8667. self.file_opened.emit("Excellon", filename)
  8668. self.file_saved.emit("Excellon", filename)
  8669. self.inform.emit('[success] %s: %s' %
  8670. (_("Excellon file exported to"), filename))
  8671. else:
  8672. return exported_excellon
  8673. except Exception as e:
  8674. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8675. return 'fail'
  8676. if use_thread is True:
  8677. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8678. def job_thread_exc(app_obj):
  8679. ret = make_excellon()
  8680. if ret == 'fail':
  8681. self.inform.emit('[ERROR_NOTCL] %s' %
  8682. _('Could not export Excellon file.'))
  8683. return
  8684. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8685. else:
  8686. ret = make_excellon()
  8687. if ret == 'fail':
  8688. self.inform.emit('[ERROR_NOTCL] %s' %
  8689. _('Could not export Excellon file.'))
  8690. return 'fail'
  8691. if local_use is not None:
  8692. return ret
  8693. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8694. """
  8695. Exports a Gerber Object to an Gerber file.
  8696. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8697. :param filename: Path to the Gerber file to save to.
  8698. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8699. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8700. :param use_thread: if to be run in a separate thread
  8701. :return:
  8702. """
  8703. self.report_usage("export_gerber()")
  8704. if filename is None:
  8705. filename = self.defaults["global_last_save_folder"]
  8706. self.log.debug("export_gerber()")
  8707. if local_use is None:
  8708. try:
  8709. obj = self.collection.get_by_name(str(obj_name))
  8710. except Exception:
  8711. # TODO: The return behavior has not been established... should raise exception?
  8712. return "Could not retrieve object: %s" % obj_name
  8713. else:
  8714. obj = local_use
  8715. # updated units
  8716. gunits = self.defaults["gerber_exp_units"]
  8717. gwhole = self.defaults["gerber_exp_integer"]
  8718. gfract = self.defaults["gerber_exp_decimals"]
  8719. gzeros = self.defaults["gerber_exp_zeros"]
  8720. fc_units = self.defaults['units'].upper()
  8721. if fc_units == 'MM':
  8722. factor = 1 if gunits == 'MM' else 0.03937
  8723. else:
  8724. factor = 25.4 if gunits == 'MM' else 1
  8725. def make_gerber():
  8726. try:
  8727. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8728. header = 'G04*\n'
  8729. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8730. (str(self.version), str(self.version_date))
  8731. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8732. header += 'G04 Created on : %s*' % time_str + '\n'
  8733. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8734. header += "%MO{units}*%\n".format(units=gunits)
  8735. for apid in obj.apertures:
  8736. if obj.apertures[apid]['type'] == 'C':
  8737. header += "%ADD{apid}{type},{size}*%\n".format(
  8738. apid=str(apid),
  8739. type='C',
  8740. size=(factor * obj.apertures[apid]['size'])
  8741. )
  8742. elif obj.apertures[apid]['type'] == 'R':
  8743. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8744. apid=str(apid),
  8745. type='R',
  8746. width=(factor * obj.apertures[apid]['width']),
  8747. height=(factor * obj.apertures[apid]['height'])
  8748. )
  8749. elif obj.apertures[apid]['type'] == 'O':
  8750. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8751. apid=str(apid),
  8752. type='O',
  8753. width=(factor * obj.apertures[apid]['width']),
  8754. height=(factor * obj.apertures[apid]['height'])
  8755. )
  8756. header += '\n'
  8757. # obsolete units but some software may need it
  8758. if gunits == 'IN':
  8759. header += 'G70*\n'
  8760. else:
  8761. header += 'G71*\n'
  8762. # Absolute Mode
  8763. header += 'G90*\n'
  8764. header += 'G01*\n'
  8765. # positive polarity
  8766. header += '%LPD*%\n'
  8767. footer = 'M02*\n'
  8768. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8769. exported_gerber = header
  8770. exported_gerber += gerber_code
  8771. exported_gerber += footer
  8772. if local_use is None:
  8773. try:
  8774. with open(filename, 'w') as fp:
  8775. fp.write(exported_gerber)
  8776. except PermissionError:
  8777. self.inform.emit('[WARNING] %s' %
  8778. _("Permission denied, saving not possible.\n"
  8779. "Most likely another app is holding the file open and not accessible."))
  8780. return 'fail'
  8781. if self.defaults["global_open_style"] is False:
  8782. self.file_opened.emit("Gerber", filename)
  8783. self.file_saved.emit("Gerber", filename)
  8784. self.inform.emit('[success] %s: %s' %
  8785. (_("Gerber file exported to"), filename))
  8786. else:
  8787. return exported_gerber
  8788. except Exception as e:
  8789. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8790. return 'fail'
  8791. if use_thread is True:
  8792. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8793. def job_thread_grb(app_obj):
  8794. ret = make_gerber()
  8795. if ret == 'fail':
  8796. self.inform.emit('[ERROR_NOTCL] %s' %
  8797. _('Could not export Gerber file.'))
  8798. return
  8799. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8800. else:
  8801. ret = make_gerber()
  8802. if ret == 'fail':
  8803. self.inform.emit('[ERROR_NOTCL] %s' %
  8804. _('Could not export Gerber file.'))
  8805. return 'fail'
  8806. if local_use is not None:
  8807. return ret
  8808. def export_dxf(self, obj_name, filename, use_thread=True):
  8809. """
  8810. Exports a Geometry Object to an DXF file.
  8811. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8812. :param filename: Path to the DXF file to save to.
  8813. :param use_thread: if to be run in a separate thread
  8814. :return:
  8815. """
  8816. self.report_usage("export_dxf()")
  8817. if filename is None:
  8818. filename = self.defaults["global_last_save_folder"]
  8819. self.log.debug("export_dxf()")
  8820. try:
  8821. obj = self.collection.get_by_name(str(obj_name))
  8822. except Exception:
  8823. # TODO: The return behavior has not been established... should raise exception?
  8824. return "Could not retrieve object: %s" % obj_name
  8825. def make_dxf():
  8826. try:
  8827. dxf_code = obj.export_dxf()
  8828. dxf_code.saveas(filename)
  8829. if self.defaults["global_open_style"] is False:
  8830. self.file_opened.emit("DXF", filename)
  8831. self.file_saved.emit("DXF", filename)
  8832. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8833. except Exception:
  8834. return 'fail'
  8835. if use_thread is True:
  8836. with self.proc_container.new(_("Exporting DXF")) as proc:
  8837. def job_thread_exc(app_obj):
  8838. ret_dxf_val = make_dxf()
  8839. if ret_dxf_val == 'fail':
  8840. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8841. return
  8842. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8843. else:
  8844. ret = make_dxf()
  8845. if ret == 'fail':
  8846. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8847. return
  8848. def import_svg(self, filename, geo_type='geometry', outname=None):
  8849. """
  8850. Adds a new Geometry Object to the projects and populates
  8851. it with shapes extracted from the SVG file.
  8852. :param filename: Path to the SVG file.
  8853. :param geo_type: Type of FlatCAM object that will be created from SVG
  8854. :param outname:
  8855. :return:
  8856. """
  8857. self.report_usage("import_svg()")
  8858. log.debug("App.import_svg()")
  8859. obj_type = ""
  8860. if geo_type is None or geo_type == "geometry":
  8861. obj_type = "geometry"
  8862. elif geo_type == "gerber":
  8863. obj_type = "gerber"
  8864. else:
  8865. self.inform.emit('[ERROR_NOTCL] %s' %
  8866. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8867. return
  8868. units = self.defaults['units'].upper()
  8869. def obj_init(geo_obj, app_obj):
  8870. geo_obj.import_svg(filename, obj_type, units=units)
  8871. geo_obj.multigeo = False
  8872. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  8873. with self.proc_container.new(_("Importing SVG")) as proc:
  8874. # Object name
  8875. name = outname or filename.split('/')[-1].split('\\')[-1]
  8876. self.new_object(obj_type, name, obj_init, autoselected=False)
  8877. # Register recent file
  8878. self.file_opened.emit("svg", filename)
  8879. # GUI feedback
  8880. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8881. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8882. """
  8883. Adds a new Geometry Object to the projects and populates
  8884. it with shapes extracted from the DXF file.
  8885. :param filename: Path to the DXF file.
  8886. :param geo_type: Type of FlatCAM object that will be created from DXF
  8887. :param outname:
  8888. :type putname: str
  8889. :return:
  8890. """
  8891. self.report_usage("import_dxf()")
  8892. obj_type = ""
  8893. if geo_type is None or geo_type == "geometry":
  8894. obj_type = "geometry"
  8895. elif geo_type == "gerber":
  8896. obj_type = geo_type
  8897. else:
  8898. self.inform.emit('[ERROR_NOTCL] %s' %
  8899. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8900. return
  8901. units = self.defaults['units'].upper()
  8902. def obj_init(geo_obj, app_obj):
  8903. geo_obj.import_dxf(filename, obj_type, units=units)
  8904. geo_obj.multigeo = False
  8905. with self.proc_container.new(_("Importing DXF")) as proc:
  8906. # Object name
  8907. name = outname or filename.split('/')[-1].split('\\')[-1]
  8908. self.new_object(obj_type, name, obj_init, autoselected=False)
  8909. self.progress.emit(20)
  8910. # Register recent file
  8911. self.file_opened.emit("dxf", filename)
  8912. # GUI feedback
  8913. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8914. self.progress.emit(100)
  8915. def open_gerber(self, filename, outname=None):
  8916. """
  8917. Opens a Gerber file, parses it and creates a new object for
  8918. it in the program. Thread-safe.
  8919. :param outname: Name of the resulting object. None causes the
  8920. name to be that of the file.
  8921. :param filename: Gerber file filename
  8922. :type filename: str
  8923. :return: None
  8924. """
  8925. # How the object should be initialized
  8926. def obj_init(gerber_obj, app_obj):
  8927. assert isinstance(gerber_obj, FlatCAMGerber), \
  8928. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8929. # Opening the file happens here
  8930. try:
  8931. gerber_obj.parse_file(filename)
  8932. except IOError:
  8933. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8934. return "fail"
  8935. except ParseError as err:
  8936. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8937. app_obj.log.error(str(err))
  8938. return "fail"
  8939. except Exception as e:
  8940. log.debug("App.open_gerber() --> %s" % str(e))
  8941. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8942. msg += traceback.format_exc()
  8943. app_obj.inform.emit(msg)
  8944. return "fail"
  8945. if gerber_obj.is_empty():
  8946. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8947. _("Object is not Gerber file or empty. Aborting object creation."))
  8948. return "fail"
  8949. App.log.debug("open_gerber()")
  8950. with self.proc_container.new(_("Opening Gerber")) as proc:
  8951. # Object name
  8952. name = outname or filename.split('/')[-1].split('\\')[-1]
  8953. # # ## Object creation # ##
  8954. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8955. if ret == 'fail':
  8956. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open Gerber failed. Probable not a Gerber file.'))
  8957. return 'fail'
  8958. # Register recent file
  8959. self.file_opened.emit("gerber", filename)
  8960. # GUI feedback
  8961. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8962. def open_excellon(self, filename, outname=None, plot=True):
  8963. """
  8964. Opens an Excellon file, parses it and creates a new object for
  8965. it in the program. Thread-safe.
  8966. :param outname: Name of the resulting object. None causes the
  8967. name to be that of the file.
  8968. :param filename: Excellon file filename
  8969. :type filename: str
  8970. :return: None
  8971. """
  8972. App.log.debug("open_excellon()")
  8973. # How the object should be initialized
  8974. def obj_init(excellon_obj, app_obj):
  8975. # self.progress.emit(20)
  8976. try:
  8977. ret = excellon_obj.parse_file(filename=filename)
  8978. if ret == "fail":
  8979. log.debug("Excellon parsing failed.")
  8980. self.inform.emit('[ERROR_NOTCL] %s' %
  8981. _("This is not Excellon file."))
  8982. return "fail"
  8983. except IOError:
  8984. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8985. (_("Cannot open file"), filename))
  8986. log.debug("Could not open Excellon object.")
  8987. self.progress.emit(0) # TODO: self and app_bjj mixed
  8988. return "fail"
  8989. except Exception:
  8990. msg = '[ERROR_NOTCL] %s' % \
  8991. _("An internal error has occurred. See shell.\n")
  8992. msg += traceback.format_exc()
  8993. app_obj.inform.emit(msg)
  8994. return "fail"
  8995. ret = excellon_obj.create_geometry()
  8996. if ret == 'fail':
  8997. log.debug("Could not create geometry for Excellon object.")
  8998. return "fail"
  8999. for tool in excellon_obj.tools:
  9000. if excellon_obj.tools[tool]['solid_geometry']:
  9001. return
  9002. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9003. (_("No geometry found in file"), filename))
  9004. return "fail"
  9005. with self.proc_container.new(_("Opening Excellon.")):
  9006. # Object name
  9007. name = outname or filename.split('/')[-1].split('\\')[-1]
  9008. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  9009. if ret_val == 'fail':
  9010. self.inform.emit('[ERROR_NOTCL] %s' %
  9011. _('Open Excellon file failed. Probable not an Excellon file.'))
  9012. return
  9013. # Register recent file
  9014. self.file_opened.emit("excellon", filename)
  9015. # GUI feedback
  9016. self.inform.emit('[success] %s: %s' %
  9017. (_("Opened"), filename))
  9018. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  9019. """
  9020. Opens a G-gcode file, parses it and creates a new object for
  9021. it in the program. Thread-safe.
  9022. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9023. :param filename: G-code file filename
  9024. :type filename: str
  9025. :return: None
  9026. """
  9027. App.log.debug("open_gcode()")
  9028. # How the object should be initialized
  9029. def obj_init(job_obj, app_obj_):
  9030. """
  9031. :param job_obj: the resulting object
  9032. :type app_obj_: App
  9033. """
  9034. assert isinstance(app_obj_, App), \
  9035. "Initializer expected App, got %s" % type(app_obj_)
  9036. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  9037. try:
  9038. f = open(filename)
  9039. gcode = f.read()
  9040. f.close()
  9041. except IOError:
  9042. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  9043. (_("Failed to open"), filename))
  9044. return "fail"
  9045. job_obj.gcode = gcode
  9046. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  9047. if gcode_ret == "fail":
  9048. self.inform.emit('[ERROR_NOTCL] %s' %
  9049. _("This is not GCODE"))
  9050. return "fail"
  9051. job_obj.create_geometry()
  9052. with self.proc_container.new(_("Opening G-Code.")):
  9053. # Object name
  9054. name = outname or filename.split('/')[-1].split('\\')[-1]
  9055. # New object creation and file processing
  9056. obj_ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  9057. if obj_ret == 'fail':
  9058. self.inform.emit('[ERROR_NOTCL] %s' %
  9059. _("Failed to create CNCJob Object. Probable not a GCode file. "
  9060. "Try to load it from File menu.\n "
  9061. "Attempting to create a FlatCAM CNCJob Object from "
  9062. "G-Code file failed during processing"))
  9063. return "fail"
  9064. # Register recent file
  9065. self.file_opened.emit("cncjob", filename)
  9066. # GUI feedback
  9067. self.inform.emit('[success] %s: %s' %
  9068. (_("Opened"), filename))
  9069. def open_script(self, filename, outname=None, silent=False):
  9070. """
  9071. Opens a Script file, parses it and creates a new object for
  9072. it in the program. Thread-safe.
  9073. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9074. :param filename: Script file filename
  9075. :type filename: str
  9076. :return: None
  9077. """
  9078. App.log.debug("open_script()")
  9079. with self.proc_container.new(_("Opening TCL Script...")):
  9080. try:
  9081. with open(filename, "r") as opened_script:
  9082. script_content = opened_script.readlines()
  9083. script_content = ''.join(script_content)
  9084. if silent is False:
  9085. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  9086. except Exception as e:
  9087. log.debug("App.open_script() -> %s" % str(e))
  9088. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  9089. return
  9090. # Object name
  9091. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  9092. # New object creation and file processing
  9093. self.on_filenewscript(name=script_name, text=script_content)
  9094. # Register recent file
  9095. self.file_opened.emit("script", filename)
  9096. # GUI feedback
  9097. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9098. def open_config_file(self, filename, run_from_arg=None):
  9099. """
  9100. Loads a config file from the specified file.
  9101. :param filename: Name of the file from which to load.
  9102. :type filename: str
  9103. :return: None
  9104. """
  9105. App.log.debug("Opening config file: " + filename)
  9106. if run_from_arg:
  9107. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9108. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9109. _("Opening FlatCAM Config file.")),
  9110. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9111. color=QtGui.QColor("gray"))
  9112. # # add the tab if it was closed
  9113. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  9114. # # first clear previous text in text editor (if any)
  9115. # self.ui.text_editor_tab.code_editor.clear()
  9116. #
  9117. # # Switch plot_area to CNCJob tab
  9118. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  9119. # close the Code editor if already open
  9120. if self.toggle_codeeditor:
  9121. self.on_toggle_code_editor()
  9122. self.on_toggle_code_editor()
  9123. try:
  9124. if filename:
  9125. f = QtCore.QFile(filename)
  9126. if f.open(QtCore.QIODevice.ReadOnly):
  9127. stream = QtCore.QTextStream(f)
  9128. code_edited = stream.readAll()
  9129. self.text_editor_tab.code_editor.setPlainText(code_edited)
  9130. f.close()
  9131. except IOError:
  9132. App.log.error("Failed to open config file: %s" % filename)
  9133. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9134. (_("Failed to open config file"), filename))
  9135. return
  9136. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  9137. """
  9138. Loads a project from the specified file.
  9139. 1) Loads and parses file
  9140. 2) Registers the file as recently opened.
  9141. 3) Calls on_file_new()
  9142. 4) Updates options
  9143. 5) Calls new_object() with the object's from_dict() as init method.
  9144. 6) Calls plot_all() if plot=True
  9145. :param filename: Name of the file from which to load.
  9146. :type filename: str
  9147. :param run_from_arg: True if run for arguments
  9148. :param plot: If True plot all objects in the project
  9149. :param cli: run from command line
  9150. :return: None
  9151. """
  9152. App.log.debug("Opening project: " + filename)
  9153. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9154. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9155. if cli is None:
  9156. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  9157. if run_from_arg:
  9158. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9159. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9160. _("Opening FlatCAM Project file.")),
  9161. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9162. color=QtGui.QColor("gray"))
  9163. # Open and parse an uncompressed Project file
  9164. try:
  9165. f = open(filename, 'r')
  9166. except IOError:
  9167. App.log.error("Failed to open project file: %s" % filename)
  9168. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9169. (_("Failed to open project file"), filename))
  9170. return
  9171. try:
  9172. d = json.load(f, object_hook=dict2obj)
  9173. except Exception as e:
  9174. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  9175. (filename, str(e)))
  9176. f.close()
  9177. # Open and parse a compressed Project file
  9178. try:
  9179. with lzma.open(filename) as f:
  9180. file_content = f.read().decode('utf-8')
  9181. d = json.loads(file_content, object_hook=dict2obj)
  9182. except Exception as e:
  9183. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  9184. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9185. (_("Failed to open project file"), filename))
  9186. return
  9187. # Clear the current project
  9188. # # NOT THREAD SAFE # ##
  9189. if run_from_arg is True:
  9190. pass
  9191. elif cli is True:
  9192. self.delete_selection_shape()
  9193. else:
  9194. self.on_file_new()
  9195. # Project options
  9196. self.options.update(d['options'])
  9197. self.project_filename = filename
  9198. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9199. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9200. if cli is None:
  9201. self.set_screen_units(self.options["units"])
  9202. # Re create objects
  9203. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9204. for obj in d['objs']:
  9205. def obj_init(obj_inst, app_inst):
  9206. obj_inst.from_dict(obj)
  9207. App.log.debug("Recreating from opened project an %s object: %s" %
  9208. (obj['kind'].capitalize(), obj['options']['name']))
  9209. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9210. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9211. if cli is None:
  9212. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9213. obj['kind'].upper(),
  9214. obj['options']['name']
  9215. )
  9216. )
  9217. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9218. self.inform.emit('[success] %s: %s' %
  9219. (_("Project loaded from"), filename))
  9220. self.should_we_save = False
  9221. self.file_opened.emit("project", filename)
  9222. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9223. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9224. if cli is None:
  9225. self.set_ui_title(name=self.project_filename)
  9226. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9227. def propagate_defaults(self, silent=False):
  9228. """
  9229. This method is used to set default values in classes. It's
  9230. an alternative to project options but allows the use
  9231. of values invisible to the user.
  9232. :return: None
  9233. """
  9234. if silent is False:
  9235. self.log.debug("propagate_defaults()")
  9236. # Which objects to update the given parameters.
  9237. routes = {
  9238. "global_zdownrate": CNCjob,
  9239. "excellon_zeros": Excellon,
  9240. "excellon_format_upper_in": Excellon,
  9241. "excellon_format_lower_in": Excellon,
  9242. "excellon_format_upper_mm": Excellon,
  9243. "excellon_format_lower_mm": Excellon,
  9244. "excellon_units": Excellon,
  9245. "gerber_use_buffer_for_union": Gerber,
  9246. "geometry_multidepth": Geometry
  9247. }
  9248. for param in routes:
  9249. if param in routes[param].defaults:
  9250. try:
  9251. routes[param].defaults[param] = self.defaults[param]
  9252. if silent is False:
  9253. self.log.debug(" " + param + " OK")
  9254. except KeyError:
  9255. if silent is False:
  9256. self.log.debug("FlatCAMApp.propagate_defaults() --> ERROR: " + param + " not in defaults.")
  9257. else:
  9258. # Try extracting the name:
  9259. # classname_param here is param in the object
  9260. if param.find(routes[param].__name__.lower() + "_") == 0:
  9261. p = param[len(routes[param].__name__) + 1:]
  9262. if p in routes[param].defaults:
  9263. routes[param].defaults[p] = self.defaults[param]
  9264. if silent is False:
  9265. self.log.debug(" " + param + " OK!")
  9266. def plot_all(self, zoom=True):
  9267. """
  9268. Re-generates all plots from all objects.
  9269. :return: None
  9270. """
  9271. self.log.debug("Plot_all()")
  9272. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9273. for obj in self.collection.get_list():
  9274. def worker_task(obj):
  9275. with self.proc_container.new("Plotting"):
  9276. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9277. if zoom:
  9278. self.object_plotted.emit(obj)
  9279. # Send to worker
  9280. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9281. def register_folder(self, filename):
  9282. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9283. def register_save_folder(self, filename):
  9284. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9285. def set_progress_bar(self, percentage, text=""):
  9286. self.ui.progress_bar.setValue(int(percentage))
  9287. def setup_shell(self):
  9288. """
  9289. Creates shell functions. Runs once at startup.
  9290. :return: None
  9291. """
  9292. self.log.debug("setup_shell()")
  9293. def shelp(p=None):
  9294. if not p:
  9295. return _("Available commands:\n") + \
  9296. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9297. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9298. if p not in commands:
  9299. return "Unknown command: %s" % p
  9300. return commands[p]["help"]
  9301. # --- Migrated to new architecture ---
  9302. # def options(name):
  9303. # ops = self.collection.get_by_name(str(name)).options
  9304. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9305. def h(*args):
  9306. """
  9307. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9308. and standalone parameters into list.
  9309. """
  9310. kwa = {}
  9311. a = []
  9312. n = len(args)
  9313. name = None
  9314. for i in range(n):
  9315. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9316. if match:
  9317. assert name is None
  9318. name = match.group(1)
  9319. continue
  9320. if name is None:
  9321. a.append(args[i])
  9322. else:
  9323. kwa[name] = args[i]
  9324. name = None
  9325. return a, kwa
  9326. @contextmanager
  9327. def wait_signal(signal, timeout=10000):
  9328. """
  9329. Block loop until signal emitted, timeout (ms) elapses
  9330. or unhandled exception happens in a thread.
  9331. :param timeout: time after which the loop is exited
  9332. :param signal: Signal to wait for.
  9333. """
  9334. loop = QtCore.QEventLoop()
  9335. # Normal termination
  9336. signal.connect(loop.quit)
  9337. # Termination by exception in thread
  9338. self.thread_exception.connect(loop.quit)
  9339. status = {'timed_out': False}
  9340. def report_quit():
  9341. status['timed_out'] = True
  9342. loop.quit()
  9343. yield
  9344. # Temporarily change how exceptions are managed.
  9345. oeh = sys.excepthook
  9346. ex = []
  9347. def except_hook(type_, value, traceback_):
  9348. ex.append(value)
  9349. oeh(type_, value, traceback_)
  9350. sys.excepthook = except_hook
  9351. # Terminate on timeout
  9352. if timeout is not None:
  9353. QtCore.QTimer.singleShot(timeout, report_quit)
  9354. # # ## Block ## ##
  9355. loop.exec_()
  9356. # Restore exception management
  9357. sys.excepthook = oeh
  9358. if ex:
  9359. self.raiseTclError(str(ex[0]))
  9360. if status['timed_out']:
  9361. raise Exception('Timed out!')
  9362. def make_docs():
  9363. output = ''
  9364. import collections
  9365. od = collections.OrderedDict(sorted(commands.items()))
  9366. for cmd_, val in od.items():
  9367. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9368. t = val['help']
  9369. usage_i = t.find('>')
  9370. if usage_i < 0:
  9371. expl = t
  9372. output += expl + '\n\n'
  9373. continue
  9374. expl = t[:usage_i - 1]
  9375. output += expl + '\n\n'
  9376. end_usage_i = t[usage_i:].find('\n')
  9377. if end_usage_i < 0:
  9378. end_usage_i = len(t[usage_i:])
  9379. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9380. else:
  9381. extras = t[usage_i+end_usage_i+1:]
  9382. parts = [s.strip() for s in extras.split('\n')]
  9383. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9384. for p in parts:
  9385. output += ' ' + p + '\n\n'
  9386. return output
  9387. '''
  9388. Howto implement TCL shell commands:
  9389. All parameters passed to command should be possible to set as None and test it afterwards.
  9390. This is because we need to see error caused in tcl,
  9391. if None value as default parameter is not allowed TCL will return empty error.
  9392. Use:
  9393. def mycommand(name=None,...):
  9394. Test it like this:
  9395. if name is None:
  9396. self.raise_tcl_error('Argument name is missing.')
  9397. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9398. otherwise we will miss it and processing will silently continue.
  9399. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9400. which is catched in exec_command and displayed in TCL shell console with red background.
  9401. Error in console is displayed with TCL trace.
  9402. This behavior works only within main thread,
  9403. errors with promissed tasks can be catched and detected only with log.
  9404. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9405. TCL shell.
  9406. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9407. '''
  9408. commands = {
  9409. 'help': {
  9410. 'fcn': shelp,
  9411. 'help': _("Shows list of commands.")
  9412. },
  9413. }
  9414. # Import/overwrite tcl commands as objects of TclCommand descendants
  9415. # This modifies the variable 'commands'.
  9416. tclCommands.register_all_commands(self, commands)
  9417. # Add commands to the tcl interpreter
  9418. for cmd in commands:
  9419. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9420. # Make the tcl puts function return instead of print to stdout
  9421. self.tcl.eval('''
  9422. rename puts original_puts
  9423. proc puts {args} {
  9424. if {[llength $args] == 1} {
  9425. return "[lindex $args 0]"
  9426. } else {
  9427. eval original_puts $args
  9428. }
  9429. }
  9430. ''')
  9431. def setup_recent_items(self):
  9432. # TODO: Move this to constructor
  9433. icons = {
  9434. "gerber": "share/flatcam_icon16.png",
  9435. "excellon": "share/drill16.png",
  9436. 'geometry': "share/geometry16.png",
  9437. "cncjob": "share/cnc16.png",
  9438. "script": "share/script_new24.png",
  9439. "document": "share/notes16_1.png",
  9440. "project": "share/project16.png",
  9441. "svg": "share/geometry16.png",
  9442. "dxf": "share/dxf16.png",
  9443. "pdf": "share/pdf32.png",
  9444. "image": "share/image16.png"
  9445. }
  9446. openers = {
  9447. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9448. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9449. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9450. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9451. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9452. "document": None,
  9453. 'project': self.open_project,
  9454. 'svg': self.import_svg,
  9455. 'dxf': self.import_dxf,
  9456. 'image': self.image_tool.import_image,
  9457. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9458. }
  9459. # Open recent file for files
  9460. try:
  9461. f = open(self.data_path + '/recent.json')
  9462. except IOError:
  9463. App.log.error("Failed to load recent item list.")
  9464. self.inform.emit('[ERROR_NOTCL] %s' %
  9465. _("Failed to load recent item list."))
  9466. return
  9467. try:
  9468. self.recent = json.load(f)
  9469. except json.scanner.JSONDecodeError:
  9470. App.log.error("Failed to parse recent item list.")
  9471. self.inform.emit('[ERROR_NOTCL] %s' %
  9472. _("Failed to parse recent item list."))
  9473. f.close()
  9474. return
  9475. f.close()
  9476. # Open recent file for projects
  9477. try:
  9478. fp = open(self.data_path + '/recent_projects.json')
  9479. except IOError:
  9480. App.log.error("Failed to load recent project item list.")
  9481. self.inform.emit('[ERROR_NOTCL] %s' %
  9482. _("Failed to load recent projects item list."))
  9483. return
  9484. try:
  9485. self.recent_projects = json.load(fp)
  9486. except json.scanner.JSONDecodeError:
  9487. App.log.error("Failed to parse recent project item list.")
  9488. self.inform.emit('[ERROR_NOTCL] %s' %
  9489. _("Failed to parse recent project item list."))
  9490. fp.close()
  9491. return
  9492. fp.close()
  9493. # Closure needed to create callbacks in a loop.
  9494. # Otherwise late binding occurs.
  9495. def make_callback(func, fname):
  9496. def opener():
  9497. func(fname)
  9498. return opener
  9499. def reset_recent_files():
  9500. # Reset menu
  9501. self.ui.recent.clear()
  9502. self.recent = []
  9503. try:
  9504. ff = open(self.data_path + '/recent.json', 'w')
  9505. except IOError:
  9506. App.log.error("Failed to open recent items file for writing.")
  9507. return
  9508. json.dump(self.recent, ff)
  9509. def reset_recent_projects():
  9510. # Reset menu
  9511. self.ui.recent_projects.clear()
  9512. self.recent_projects = []
  9513. try:
  9514. fp = open(self.data_path + '/recent_projects.json', 'w')
  9515. except IOError:
  9516. App.log.error("Failed to open recent projects items file for writing.")
  9517. return
  9518. json.dump(self.recent, fp)
  9519. # Reset menu
  9520. self.ui.recent.clear()
  9521. self.ui.recent_projects.clear()
  9522. # Create menu items for projects
  9523. for recent in self.recent_projects:
  9524. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9525. if recent['kind'] == 'project':
  9526. try:
  9527. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9528. # Attach callback
  9529. o = make_callback(openers[recent["kind"]], recent['filename'])
  9530. action.triggered.connect(o)
  9531. self.ui.recent_projects.addAction(action)
  9532. except KeyError:
  9533. App.log.error("Unsupported file type: %s" % recent["kind"])
  9534. # Last action in Recent Files menu is one that Clear the content
  9535. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent projects")), self)
  9536. clear_action_proj.triggered.connect(reset_recent_projects)
  9537. self.ui.recent_projects.addSeparator()
  9538. self.ui.recent_projects.addAction(clear_action_proj)
  9539. # Create menu items for files
  9540. for recent in self.recent:
  9541. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9542. if recent['kind'] != 'project':
  9543. try:
  9544. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9545. # Attach callback
  9546. o = make_callback(openers[recent["kind"]], recent['filename'])
  9547. action.triggered.connect(o)
  9548. self.ui.recent.addAction(action)
  9549. except KeyError:
  9550. App.log.error("Unsupported file type: %s" % recent["kind"])
  9551. # Last action in Recent Files menu is one that Clear the content
  9552. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9553. clear_action.triggered.connect(reset_recent_files)
  9554. self.ui.recent.addSeparator()
  9555. self.ui.recent.addAction(clear_action)
  9556. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9557. # self.ui.menufilerecent.set_submenu(recent_menu)
  9558. # recent_menu.show_all()
  9559. # self.ui.recent.show()
  9560. self.log.debug("Recent items list has been populated.")
  9561. def setup_component_editor(self):
  9562. # label = QtWidgets.QLabel("Choose an item from Project")
  9563. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9564. sel_title = QtWidgets.QTextEdit(
  9565. _('<b>Shortcut Key List</b>'))
  9566. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9567. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9568. settings = QSettings("Open Source", "FlatCAM")
  9569. if settings.contains("notebook_font_size"):
  9570. fsize = settings.value('notebook_font_size', type=int)
  9571. else:
  9572. fsize = 12
  9573. tsize = fsize + int(fsize / 2)
  9574. # selected_text = (_('''
  9575. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9576. #
  9577. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9578. # The normal flow when working in FlatCAM is the following:</span></p>
  9579. #
  9580. # <ol>
  9581. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9582. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9583. # even dragging and dropping the files on the GUI.<br />
  9584. # <br />
  9585. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9586. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9587. # &nbsp;</li>
  9588. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9589. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9590. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9591. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9592. # <br />
  9593. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9594. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9595. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9596. # it even if it was out of focus.<br />
  9597. # <br />
  9598. # You can change the parameters in this screen and the flow direction is like this:<br />
  9599. # <br />
  9600. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9601. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9602. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9603. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9604. # </ol>
  9605. #
  9606. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9607. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9608. # <strong>F3</strong>.</span></p>
  9609. #
  9610. # ''').format(fsize=fsize, tsize=tsize))
  9611. selected_text = '''
  9612. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9613. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9614. {s1}</span></p>
  9615. <ol>
  9616. <li><span style="font-size:{fsize}px">{s2}<br />
  9617. <br />
  9618. {s3}</span><br />
  9619. &nbsp;</li>
  9620. <li><span style="font-size:{fsize}px">{s4}<br />
  9621. &nbsp;</li>
  9622. <br />
  9623. <li><span style="font-size:{fsize}px">{s5}<br />
  9624. &nbsp;</li>
  9625. <br />
  9626. <li><span style="font-size:{fsize}px">{s6}<br />
  9627. <br />
  9628. {s7}</span></li>
  9629. </ol>
  9630. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9631. '''.format(
  9632. title=_("Selected Tab - Choose an Item from Project Tab"),
  9633. subtitle=_("Details"),
  9634. s1=_("The normal flow when working in FlatCAM is the following:"),
  9635. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9636. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9637. "files on the GUI."),
  9638. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9639. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9640. "actions offered within the app."),
  9641. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9642. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9643. "SELECTED TAB will be updated with the object properties according to its kind: "
  9644. "Gerber, Excellon, Geometry or CNCJob object."),
  9645. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9646. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9647. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9648. "the SELECTED TAB and populate it even if it was out of focus."),
  9649. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9650. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9651. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9652. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9653. "(again, done in SELECTED TAB) --> Save GCode."),
  9654. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9655. "or through its own key shortcut: <b>F3</b>."),
  9656. tsize=tsize,
  9657. fsize=fsize
  9658. )
  9659. sel_title.setText(selected_text)
  9660. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9661. self.ui.selected_scroll_area.setWidget(sel_title)
  9662. def setup_obj_classes(self):
  9663. """
  9664. Sets up application specifics on the FlatCAMObj class.
  9665. :return: None
  9666. """
  9667. FlatCAMObj.app = self
  9668. ObjectCollection.app = self
  9669. Gerber.app = self
  9670. Excellon.app = self
  9671. Geometry.app = self
  9672. CNCjob.app = self
  9673. FCProcess.app = self
  9674. FCProcessContainer.app = self
  9675. def version_check(self):
  9676. """
  9677. Checks for the latest version of the program. Alerts the
  9678. user if theirs is outdated. This method is meant to be run
  9679. in a separate thread.
  9680. :return: None
  9681. """
  9682. self.log.debug("version_check()")
  9683. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9684. full_url = App.version_url + \
  9685. "?s=" + str(self.defaults['global_serial']) + \
  9686. "&v=" + str(self.version) + \
  9687. "&os=" + str(self.os) + \
  9688. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9689. else:
  9690. # no_stats dict; just so it won't break things on website
  9691. no_ststs_dict = {}
  9692. no_ststs_dict["global_ststs"] = {}
  9693. full_url = App.version_url + \
  9694. "?s=" + str(self.defaults['global_serial']) + \
  9695. "&v=" + str(self.version) + \
  9696. "&os=" + str(self.os) + \
  9697. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9698. App.log.debug("Checking for updates @ %s" % full_url)
  9699. # ## Get the data
  9700. try:
  9701. f = urllib.request.urlopen(full_url)
  9702. except Exception:
  9703. # App.log.warning("Failed checking for latest version. Could not connect.")
  9704. self.log.warning("Failed checking for latest version. Could not connect.")
  9705. self.inform.emit('[WARNING_NOTCL] %s' %
  9706. _("Failed checking for latest version. Could not connect."))
  9707. return
  9708. try:
  9709. data = json.load(f)
  9710. except Exception as e:
  9711. App.log.error("Could not parse information about latest version.")
  9712. self.inform.emit('[ERROR_NOTCL] %s' %
  9713. _("Could not parse information about latest version."))
  9714. App.log.debug("json.load(): %s" % str(e))
  9715. f.close()
  9716. return
  9717. f.close()
  9718. # ## Latest version?
  9719. if self.version >= data["version"]:
  9720. App.log.debug("FlatCAM is up to date!")
  9721. self.inform.emit('[success] %s' %
  9722. _("FlatCAM is up to date!"))
  9723. return
  9724. App.log.debug("Newer version available.")
  9725. self.message.emit(
  9726. _("Newer Version Available"),
  9727. _("There is a newer version of FlatCAM available for download:\n\n") +
  9728. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9729. _("info")
  9730. )
  9731. def on_plotcanvas_setup(self, container=None):
  9732. """
  9733. This is doing the setup for the plot area (VisPy canvas)
  9734. :param container: widget where to install the canvas
  9735. :return: None
  9736. """
  9737. if container:
  9738. plot_container = container
  9739. else:
  9740. plot_container = self.ui.right_layout
  9741. if self.is_legacy is False:
  9742. self.plotcanvas = PlotCanvas(plot_container, self)
  9743. else:
  9744. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9745. # So it can receive key presses
  9746. self.plotcanvas.native.setFocus()
  9747. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9748. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9749. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9750. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  9751. # Keys over plot enabled
  9752. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9753. if self.defaults['global_cursor_type'] == 'small':
  9754. self.app_cursor = self.plotcanvas.new_cursor()
  9755. else:
  9756. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9757. if self.ui.grid_snap_btn.isChecked():
  9758. self.app_cursor.enabled = True
  9759. else:
  9760. self.app_cursor.enabled = False
  9761. if self.is_legacy is False:
  9762. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9763. else:
  9764. # will use the default Matplotlib axes
  9765. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9766. def on_zoom_fit(self, event):
  9767. """
  9768. Callback for zoom-out request. This can be either from the corresponding
  9769. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9770. with axes limits from the geometry bounds of all objects.
  9771. :param event: Ignored.
  9772. :return: None
  9773. """
  9774. if self.is_legacy is False:
  9775. self.plotcanvas.fit_view()
  9776. else:
  9777. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9778. width = xmax - xmin
  9779. height = ymax - ymin
  9780. xmin -= 0.05 * width
  9781. xmax += 0.05 * width
  9782. ymin -= 0.05 * height
  9783. ymax += 0.05 * height
  9784. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9785. def on_zoom_in(self):
  9786. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9787. def on_zoom_out(self):
  9788. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9789. def disable_all_plots(self):
  9790. self.report_usage("disable_all_plots()")
  9791. self.disable_plots(self.collection.get_list())
  9792. self.inform.emit('[success] %s' %
  9793. _("All plots disabled."))
  9794. def disable_other_plots(self):
  9795. self.report_usage("disable_other_plots()")
  9796. self.disable_plots(self.collection.get_non_selected())
  9797. self.inform.emit('[success] %s' %
  9798. _("All non selected plots disabled."))
  9799. def enable_all_plots(self):
  9800. self.report_usage("enable_all_plots()")
  9801. self.enable_plots(self.collection.get_list())
  9802. self.inform.emit('[success] %s' %
  9803. _("All plots enabled."))
  9804. def on_enable_sel_plots(self):
  9805. log.debug("App.on_enable_sel_plot()")
  9806. object_list = self.collection.get_selected()
  9807. self.enable_plots(objects=object_list)
  9808. self.inform.emit('[success] %s' %
  9809. _("Selected plots enabled..."))
  9810. def on_disable_sel_plots(self):
  9811. log.debug("App.on_disable_sel_plot()")
  9812. # self.inform.emit(_("Disabling plots ..."))
  9813. object_list = self.collection.get_selected()
  9814. self.disable_plots(objects=object_list)
  9815. self.inform.emit('[success] %s' %
  9816. _("Selected plots disabled..."))
  9817. def enable_plots(self, objects):
  9818. """
  9819. Disables plots
  9820. :param objects: list of Objects to be enabled
  9821. :return:
  9822. """
  9823. log.debug("Enabling plots ...")
  9824. # self.inform.emit(_("Working ..."))
  9825. for obj in objects:
  9826. if obj.options['plot'] is False:
  9827. obj.options.set_change_callback(lambda x: None)
  9828. obj.options['plot'] = True
  9829. obj.options.set_change_callback(obj.on_options_change)
  9830. def worker_task(objs):
  9831. with self.proc_container.new(_("Enabling plots ...")):
  9832. for obj in objs:
  9833. # obj.options['plot'] = True
  9834. if isinstance(obj, FlatCAMCNCjob):
  9835. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9836. else:
  9837. obj.plot(visible=True)
  9838. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9839. # self.plots_updated.emit()
  9840. def disable_plots(self, objects):
  9841. """
  9842. Disables plots
  9843. :param objects: list of Objects to be disabled
  9844. :return:
  9845. """
  9846. # if no objects selected then do nothing
  9847. if not self.collection.get_selected():
  9848. return
  9849. log.debug("Disabling plots ...")
  9850. # self.inform.emit(_("Working ..."))
  9851. for obj in objects:
  9852. if obj.options['plot'] is True:
  9853. obj.options.set_change_callback(lambda x: None)
  9854. obj.options['plot'] = False
  9855. obj.options.set_change_callback(obj.on_options_change)
  9856. try:
  9857. self.delete_selection_shape()
  9858. except Exception as e:
  9859. log.debug("App.disable_plots() --> %s" % str(e))
  9860. # self.plots_updated.emit()
  9861. def worker_task(objs):
  9862. with self.proc_container.new(_("Disabling plots ...")):
  9863. for obj in objs:
  9864. # obj.options['plot'] = True
  9865. if isinstance(obj, FlatCAMCNCjob):
  9866. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9867. else:
  9868. obj.plot(visible=False)
  9869. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9870. def toggle_plots(self, objects):
  9871. """
  9872. Toggle plots visibility
  9873. :param objects: list of Objects for which to be toggled the visibility
  9874. :return:
  9875. """
  9876. # if no objects selected then do nothing
  9877. if not self.collection.get_selected():
  9878. return
  9879. log.debug("Toggling plots ...")
  9880. self.inform.emit(_("Working ..."))
  9881. for obj in objects:
  9882. if obj.options['plot'] is False:
  9883. obj.options['plot'] = True
  9884. else:
  9885. obj.options['plot'] = False
  9886. self.plots_updated.emit()
  9887. def clear_plots(self):
  9888. objects = self.collection.get_list()
  9889. for obj in objects:
  9890. obj.clear(obj == objects[-1])
  9891. # Clear pool to free memory
  9892. self.clear_pool()
  9893. def generate_cnc_job(self, objects):
  9894. self.report_usage("generate_cnc_job()")
  9895. # for obj in objects:
  9896. # obj.generatecncjob()
  9897. for obj in objects:
  9898. obj.on_generatecnc_button_click()
  9899. def save_project(self, filename, quit_action=False, silent=False):
  9900. """
  9901. Saves the current project to the specified file.
  9902. :param filename: Name of the file in which to save.
  9903. :type filename: str
  9904. :param quit_action: if the project saving will be followed by an app quit; boolean
  9905. :param silent: if True will not display status messages
  9906. :return: None
  9907. """
  9908. self.log.debug("save_project()")
  9909. self.save_in_progress = True
  9910. with self.proc_container.new(_("Saving FlatCAM Project")):
  9911. # Capture the latest changes
  9912. # Current object
  9913. try:
  9914. self.collection.get_active().read_form()
  9915. except Exception as e:
  9916. self.log.debug("There was no active object. %s" % str(e))
  9917. pass
  9918. # Serialize the whole project
  9919. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9920. "options": self.options,
  9921. "version": self.version}
  9922. if self.defaults["global_save_compressed"] is True:
  9923. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9924. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9925. # # Write
  9926. f.write(g)
  9927. self.inform.emit('[success] %s: %s' %
  9928. (_("Project saved to"), filename))
  9929. else:
  9930. # Open file
  9931. try:
  9932. f = open(filename, 'w')
  9933. except IOError:
  9934. App.log.error("Failed to open file for saving: %s", filename)
  9935. return
  9936. # Write
  9937. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9938. f.close()
  9939. # verification of the saved project
  9940. # Open and parse
  9941. try:
  9942. saved_f = open(filename, 'r')
  9943. except IOError:
  9944. if silent is False:
  9945. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9946. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9947. )
  9948. return
  9949. try:
  9950. saved_d = json.load(saved_f, object_hook=dict2obj)
  9951. except Exception:
  9952. if silent is False:
  9953. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9954. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9955. )
  9956. f.close()
  9957. return
  9958. saved_f.close()
  9959. if silent is False:
  9960. if 'version' in saved_d:
  9961. self.inform.emit('[success] %s: %s' %
  9962. (_("Project saved to"), filename))
  9963. else:
  9964. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9965. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9966. )
  9967. tb_settings = QSettings("Open Source", "FlatCAM")
  9968. lock_state = self.ui.lock_action.isChecked()
  9969. tb_settings.setValue('toolbar_lock', lock_state)
  9970. # This will write the setting to the platform specific storage.
  9971. del tb_settings
  9972. # if quit:
  9973. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9974. # t.start()
  9975. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9976. def start_delayed_quit(self, delay, filename, should_quit=None):
  9977. """
  9978. :param delay: period of checking if project file size is more than zero; in seconds
  9979. :param filename: the name of the project file to be checked periodically for size more than zero
  9980. :param should_quit: if the task finished will be followed by an app quit; boolean
  9981. :return:
  9982. """
  9983. to_quit = should_quit
  9984. self.save_timer = QtCore.QTimer()
  9985. self.save_timer.setInterval(delay)
  9986. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9987. self.save_timer.start()
  9988. def check_project_file_size(self, filename, should_quit=None):
  9989. """
  9990. :param filename: the name of the project file to be checked periodically for size more than zero
  9991. :param should_quit: will quit the app if True; boolean
  9992. :return:
  9993. """
  9994. try:
  9995. if os.stat(filename).st_size > 0:
  9996. self.save_in_progress = False
  9997. self.save_timer.stop()
  9998. if should_quit:
  9999. self.app_quit.emit()
  10000. except Exception:
  10001. traceback.print_exc()
  10002. def on_plotarea_tab_closed(self, tab_idx):
  10003. widget = self.ui.plot_tab_area.widget(tab_idx)
  10004. if widget is not None:
  10005. widget.deleteLater()
  10006. self.ui.plot_tab_area.removeTab(tab_idx)
  10007. def on_options_app2project(self):
  10008. """
  10009. Callback for Options->Transfer Options->App=>Project. Copies options
  10010. from application defaults to project defaults.
  10011. :return: None
  10012. """
  10013. self.report_usage("on_options_app2project")
  10014. self.defaults_read_form()
  10015. self.options.update(self.defaults)
  10016. # self.options_write_form()
  10017. class ArgsThread(QtCore.QObject):
  10018. open_signal = pyqtSignal(list)
  10019. start = pyqtSignal()
  10020. if sys.platform == 'win32':
  10021. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  10022. else:
  10023. address = ('/tmp/testipc', 'AF_UNIX')
  10024. def __init__(self):
  10025. super(ArgsThread, self).__init__()
  10026. self.start.connect(self.run)
  10027. def my_loop(self, address):
  10028. try:
  10029. listener = Listener(*address)
  10030. while True:
  10031. conn = listener.accept()
  10032. self.serve(conn)
  10033. except socket.error:
  10034. conn = Client(*address)
  10035. conn.send(sys.argv)
  10036. conn.send('close')
  10037. # close the current instance only if there are args
  10038. if len(sys.argv) > 1:
  10039. sys.exit()
  10040. def serve(self, conn):
  10041. while True:
  10042. msg = conn.recv()
  10043. if msg == 'close':
  10044. break
  10045. self.open_signal.emit(msg)
  10046. conn.close()
  10047. # the decorator is a must; without it this technique will not work unless the start signal is connected
  10048. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  10049. @pyqtSlot()
  10050. def run(self):
  10051. self.my_loop(self.address)
  10052. class GracefulException(Exception):
  10053. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  10054. def __init__(self):
  10055. super().__init__()
  10056. def __str__(self):
  10057. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  10058. # end of file