FlatCAMApp.py 364 KB

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